First, define the function
// 1.function
const AAA = function () {
}
// 2. functions defined object literal
const obj = {
BBB () {
}
}
// arrow in the function 3.ES6
const = CCC (parameter) => {
}
Second, the parameters and return values of the function arrow
1, the parameters of the problem
// 1.1 two parameters
const = SUM (num1, num2) => {
return num1 + num2
}
// 1.2 parameter (in parentheses may be omitted)
const = Power NUM => {
return NUM * NUM
}
2, the return value
@ When the code block 2.1 normal write multiple lines of code
const Test = () => {
the console.log ( '11111' )
the console.log ( '22222' )
}
// omitted when a large block of code with a 2.2 line of code brackets
const power = num => num * num
Third, the function of this arrow
// 1. When using the arrow function function: When the function as an argument another function of
the setTimeout ( function () {
the console.log ( the this ) // window
}, 1000 )
the setTimeout (() => {
Console .log ( the this ) // window
}, 1000 )
const obj = {
AAA () {
the setTimeout ( function () { // function call by call, call as the first parameter window will pass in
the console.log ( the this ) // window
})
the setTimeout (() => { //Arrow function does not own this, only to find out layer by layer
the console.log ( the this ) // AAA Object obj
})
}
}
obj.aaa ()
const obj = {
AAA () {
the setTimeout ( function () { // function call is passed through into the call, call as the first parameter window will
the setTimeout ( function () {
the console.log ( the this ) // window
})
the setTimeout (() => {
the console.log ( the this ) / / window
})
})
the setTimeout (() => { // arrow function does not own this, only one layer outwardly scope find out
the setTimeout ( function () {
the console.log ( the this ) // window
})
the setTimeout (() => {
the console.log ( the this ) // AAA Object obj
})
})
}
}
obj.aaa ()
to sum up:
Arrow function does not own this, he is in the definition of the function of time-bound and not bound in the implementation process, it inherits the object-defined function, for example:
function Person () {
this.name = 'lihh',
this.age = 18,
setInterval(() => {
console.log (this)
console.log('我叫' + this.name + '今年' + this.age)
}, 1000);
}
let p = new Person()
打印结果是this指向了Person
再看下面这种非箭头函数:
function Person () {
this.name = 'lihh',
this.age = 18,
setInterval(function () {
console.log (this)
console.log('我叫' + this.name + '今年' + this.age)
}, 1000);
}
let p = new Person()
打印结果是this指向了window,这是由于setInterval跟setTimeout调用的代码运行在与所在函数完全分离的执行环境上。这会导致这些代码中包含的 this 关键字会指向 window (或全局)对象。
四、使用箭头函数的好处
1.解决了匿名函数的this指向问题
上面例子打印结果为undefined,是因为此时this指向的是window对象,然而window对象上面并没有绑定name和age属性,所以找不到
五、什么时候不能使用箭头函数
(待补充)