ES6 new syntax of Arrow Function
Arrow Function.md
Arrow Functions
The basic syntax of an arrow function is as follows
var fn = data => data;
The code means :
var fn = function( data ) {
return data;
}
let getNumber = () => 42;
console.log(typeof getNumber);
console.log(getNumber());
var getPrice = (quantity,tax) => (quantity * 5) + (1 + tax);
console.log(getPrice(2,.095));
var getPrice = (quantity,tax) => {
let price = (quantity * 5)
price *= (1 + tax);
return price;
}
console.log(getPrice(2,.095));
var getNumber = data => ({data: 'check', number: 42});
var getNumber = function(data) {
return {
data:'check',
number: 42
}
}
How create IIFEs using arrow function?
var fn = function( number) {
return {
getNumber: function(){
return number;
}
}
}(42);
console.log(fn.getNumber);
Why we use IIFEs?
This is an effective pattern to shield the expression from the rest of program.
var fn = ((number) => {
return {
getNumber: function() {
return number;
}
}
})(42);
console.log(fn.getNumber());
Difference of function expressions and function declarations
Arrow function do save us a few lines of code and characters ,but the real purpose of the arrow funcion is to handlethe this keyword within functions. this behaves differently inside an arrow function.
Let's take a look at how the this keyword work in general
A tale about this
1.Function Invocation
function getContext(){
console.log(this);
}
getContext() is a Window/Global object.At the time getContext() is called,JavaScript automatically sets this at the global object,which in browser is Window.
if(this === window){
console.log('This refers to the global context')
}
2.Method Invocation
let myObj = {
name: 'fancy',
opration: function(){
console.log(this)
}
}
myObj.opration();
let x = myObj.opration;
x();
let x = myObj.opration;
x();
x.call(myObj);
//myObj.x()?
3.Construtor Invocation
what is constructor invocation?
Constructor invocation happens when an object is created using the new keyword.
function Employee( name, department, salary){
this.name = name;
this.department = department;
this.salary = salary;
console.log('Welcome'+this.name+"!");
}
let john = new Employee('Johe', 'Sales', 4000 );
this in arrow funcion
Arrow function are designed to lexically bind the
context ,which means that this refers to the enclosing
context where the arrow funcion is defined.Unlike a
normal function, arrow function does not create its
own excution context,but takes this from outer function
where it is defined.
function Employee(firstName, department, salary){
this.firstName = firstName;
this.department = department;
this.salary = salary;
this.getInfo = function(){
return function(){
console.log(this.firstName + " from " +
this.department + " earns " + this.salary
);
}
}
}
let jim = new Employee('Jim', 'Finance', '5200');
let printInfo = jim.getInfo();
printInfo();
In this section, Employee is a construtor function and
we created a new employee object called jim using the
constructor function with the new keyword.In order to
print the employee information,we need using the function
returned by jim.getInfo().
Here,printInfo refers to the inner function and since
we are simply making a function invocation,this refers to
the Global object that does not have any Employee properties
and hence produces undefined whenever a property on this is
used.
In the section,we replace the inner function with an arrow function.
In this case,the this keyword refers to the context of the function
enclosing the arrow function unlike the previous case where it referred
the Global object.At the point,it is important to note that arrow functions
do not change their context on invocation.
function Employee(firstName, department, salary) {
this.firstName = firstName;
this.department = department;
this.salary = salary;
this.getInfo = function(){
return() => {
console.log(this.firstName + " from " +
this.department + " earns " + this.salary);
};
}
}
let jim = new Employee ('Jim', 'Finance', 5200);
let printInfo = jim.getInfo();
printInfo();
function Employee(){
this.firstName = "Jack",
this.department = "HR",
this.salary = 4500,
this.getContext = () => {
console.log(this);
}
let mark = new Employee();
mark.getContext();
let context = mark.getContext;
context();
}
In the above example,the context of the arrow function was set
on declaration and it cannot be changed.An important thing to note
here is that you cannot "rebind" an arrow funtion.The context
always fixed.
var details = {
number: 42,
opration: function(){
return () => console.log(this.number);
}
};
var details = {
number: 84
};
details.opration().bind(details2)();
In the example,we are setting the details2 number to 84.But we
now we can't bind a new object to arrow function.The engine does
not throw any error,it just ingores the bind completely. So
42 is printed even if we call the opration method with the details2
object.This also applies to call and apply.So with an arrow function,
calls to bind,call or apply will not be able to change to value
of this.
var product = ( x, y ) => x * y;
console.log(product.call(null,2,3));
console.log(product.apply(null, [2,3]));
var multiply = product.bind(null, 2, 3);
console.log(multiply());
var newFn = () => { },
object = new newFn();
var details = () => 42;
console.log(details.hasOwnProperty("prototype"));
Using arrow function
So,whenever you have a short single-statement inline function
expression,with a computed return value and the function does not
make a reference a self-reference,you can replace it with an
arrow function.
$('.btn').on('click', function(){
var self = this;
setTimeout({
$(self).toggleClass('btn-active');
},1000);
});
$('.btn').on('click',function(){
setTimeout(() => {
$(this).toggleClass('btn-active');
},1000);
});
ES6 new syntax of Arrow Function的更多相关文章
- ES6 new syntax of Default Function Parameters
Default Function Parameters.md Default Function Parameters function getSum(a,b){ a = (a !== undefine ...
- es6语法中的arrow function=>
(x) => x + 相当于 function(x){ ; }; var ids = this.sels.map(item => item.id).join() var ids = thi ...
- ES6 箭头函数(arrow function)
例行声明:接下来的文字内容全部来自 Understanding ECMAScript 6,作者是Nicholas C.Zakas,也就是大名鼎鼎的Professional JavaScript for ...
- [ES6系列-02]Arrow Function:Whats this?(箭头函数及它的this及其它)
[原创] 码路工人 大家好,这里是码路工人有力量,我是码路工人,你们是力量. 如果没用过CSharp的lambda 表达式,也没有了解过ES6,那第一眼看到这样代码什么感觉? /* eg.0 * fu ...
- [ES6] 06. Arrow Function =>
ES6 arrow function is somehow like CoffeeScirpt. CoffeeScript: //function call coffee = -> coffee ...
- vue & lifecycle methods & this bug & ES6 Arrow function & this bind bug
vue & lifecycle methods & this bug ES6 Arrow function & this bind bug bad fetchTableData ...
- ES6 Arrow Function & this bug
ES6 Arrow Function & this bug let accHeadings = document.querySelectorAll(`.accordionItemHeading ...
- ES6 Arrow Function All In One
ES6 Arrow Function All In One this const log = console.log; const arrow_func = (args) => log(`arg ...
- ES6 arrow function vs ES5 function
ES6 arrow function vs ES5 function ES6 arrow function 与 ES5 function 区别 this refs xgqfrms 2012-2020 ...
随机推荐
- 新手立体四子棋AI教程(3)——极值搜索与Alpha-Beta剪枝
上一篇我们讲了评估函数,这一篇我们来讲讲立体四子棋的搜索函数. 一.极值搜索 极值搜索是game playing领域里非常经典的算法,它使用深度优先搜索(因为限制最大层数,所以也可以称为迭代加深搜索) ...
- Android,资料分享(2015 版)
Java 学习 我要再次强调,一定要有Java 基础(虽然现在使用其他语言也可以开发Android,但毕竟是很小众),也不要认为学习Java 两三周就可以不用管了,这会在以后的深入学习中暴露出问题,所 ...
- 使用listview空控件展示数据
1.使用listview控件可以一次性的将有关的全部图像保存在控件中,建立集合图像. 图像列表控件的主要属性 属性 ...
- 键值编码KVC
动态设置:setValue:属性值 forKey:属性名用于简单路径:setValue:属性值 forKeyPath:属性路径用于复合路径,例如Person有一个Account类型的属性,那么pers ...
- unittest自动化使用HTMLTestRunner的中文编码问题
1.使用unittest自动化测试框架,使用HTMLTestRunner生成测试报告,中文乱码问题! 如图 2.解决方法: 第一步:先在自己的测试脚本中添加 import sys reload(sys ...
- rtmp发布录制视频
本文描述了rtmp发布本地视频的流程 一.简要介绍 RTMP协议规定,播放一个流媒体有两个前提步骤:第一步,建立一个网络连接(NetConnection):第二步,建立一个网络流(NetStream) ...
- 20162320刘先润第三周Bag类测试
前言 以下内容是本周Bag代码的课后作业,要求是完成伪代码.产品代码和测试代码,为了书写方便我将伪代码以注释的形式写在了产品代码的后面 测试步骤 1.首先对Bag类引用BagInterface的代码进 ...
- 十款不容错过的Swift iOS开源项目及介绍
1.十款不容错过的Swift iOS开源项目. http://www.csdn.net/article/2014-10-16/2822083-swift-ios-open-source-project ...
- 200行Python代码实现2048
200行Python代码实现2048 一.实验说明 1. 环境登录 无需密码自动登录,系统用户名shiyanlou 2. 环境介绍 本实验环境采用带桌面的Ubuntu Linux环境,实验中会用到桌面 ...
- WPF自学入门(十)WPF MVVM简单介绍
前面文章中,我们已经知道,WPF技术的主要特点是数据驱动UI,所以在使用WPF技术开发的过程中是以数据为核心的,WPF提供了数据绑定机制,当数据发生变化时,WPF会自动发出通知去更新UI. 我们不管 ...