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的更多相关文章

  1. ES6 new syntax of Default Function Parameters

    Default Function Parameters.md Default Function Parameters function getSum(a,b){ a = (a !== undefine ...

  2. es6语法中的arrow function=>

    (x) => x + 相当于 function(x){ ; }; var ids = this.sels.map(item => item.id).join() var ids = thi ...

  3. ES6 箭头函数(arrow function)

    例行声明:接下来的文字内容全部来自 Understanding ECMAScript 6,作者是Nicholas C.Zakas,也就是大名鼎鼎的Professional JavaScript for ...

  4. [ES6系列-02]Arrow Function:Whats this?(箭头函数及它的this及其它)

    [原创] 码路工人 大家好,这里是码路工人有力量,我是码路工人,你们是力量. 如果没用过CSharp的lambda 表达式,也没有了解过ES6,那第一眼看到这样代码什么感觉? /* eg.0 * fu ...

  5. [ES6] 06. Arrow Function =>

    ES6 arrow function is somehow like CoffeeScirpt. CoffeeScript: //function call coffee = -> coffee ...

  6. vue & lifecycle methods & this bug & ES6 Arrow function & this bind bug

    vue & lifecycle methods & this bug ES6 Arrow function & this bind bug bad fetchTableData ...

  7. ES6 Arrow Function & this bug

    ES6 Arrow Function & this bug let accHeadings = document.querySelectorAll(`.accordionItemHeading ...

  8. ES6 Arrow Function All In One

    ES6 Arrow Function All In One this const log = console.log; const arrow_func = (args) => log(`arg ...

  9. ES6 arrow function vs ES5 function

    ES6 arrow function vs ES5 function ES6 arrow function 与 ES5 function 区别 this refs xgqfrms 2012-2020 ...

随机推荐

  1. xml解析多个结点方法(C#)

    解析多个结点的XML文件,格式如下: <?xml version="1.0" encoding="utf-8"?> <response> ...

  2. js和jquery判断checkbox是否被选中

    js判断: if(document.getElementById("checkboxID").checked){ alert("checkbox is checked&q ...

  3. drbd(二):配置和使用

    本文目录:1.drbd配置文件2.创建metadata区并计算metadata区的大小3.启动drbd4.实现drbd主从同步5.数据同步和主从角色切换6.drbd脑裂后的解决办法7.drbd多卷组配 ...

  4. Flume日志采集系统

    1.简介 Flume是Cloudera提供的一个高可用.高可靠.分布式的海量日志采集.聚合和传输的系统. Flume支持在日志系统中定制各类数据发送方用于收集数据,同时Flume提供对数据进行简单的处 ...

  5. Struts2——第一个helloworld页面

    struts2是一个较为成熟的mvc框架,先看看怎么配置struts2并且产生helloworld页面. 首先从官网下载struts2,http://struts.apache.org/downloa ...

  6. JavaScript(第二十七天)【错误处理与调试】

    JavaScript在错误处理调试上一直是它的软肋,如果脚本出错,给出的提示经常也让人摸不着头脑.ECMAScript第3版为了解决这个问题引入了try...catch和throw语句以及一些错误类型 ...

  7. 福州大学W班-需求分析评分排名

    作业链接 https://edu.cnblogs.com/campus/fzu/FZUSoftwareEngineering1715W/homework/1019 作业要求 1.需求文档 1) 参考& ...

  8. 凡事预则立(Beta)

    听说--凡事预则立 吸取之前alpha冲刺的经验教训,也为了这次的beta冲刺可以更好更顺利地进行,更是为了迎接我们的新成员玮诗.我们开了一次组内会议,进行beta冲刺的规划. 上一张我们的合照: 具 ...

  9. 【Alpha版本】冲刺阶段 - Day2 - 漂流

    今日进展 袁逸灏:实现车辆的子弹发射(3.5h) 启动类,子弹类(修改类),游戏画面类(修改类) 刘伟康:继续借鉴其他 alpha 冲刺博客,初步了解墨刀.leangoo等工具(2h) 刘先润:解决了 ...

  10. 【Alpha版本】冲刺阶段 - Day3 - 逆风

    今日进展 袁逸灏:右上角两个按键的添加与实现监听(5h) 刘伟康:继续借鉴其他 alpha 冲刺博客,由于我们组的App原型可以在 alpha 阶段完成,所以不需要墨刀工具展示原型(2h) 刘先润:更 ...