ES6中的特殊函数类型:箭头函数,不使用function
默认的this
绑定规则。
箭头函数的this
取决于其外层作用域的this
绑定情况:
function test(){
return ()=>{
console.log(this.a)
}
}
var obj1 = {
a:1
}
var obj2 = {
a:2
}
var bar = test.call(obj1)
bar.call(obj2) // 结果为1
// test内部的箭头函数在第一次调用test时(test函数的执行),进行了定义,此时被test函数绑定为obj1
// 箭头函数取决于其外部代码块绑定的this
// 因此后面再执行也不会改变this的绑定
箭头函数内部的this
会绑定为其定义时的所在的对象,其原因为箭头函数内部没有this
,因此它的this
为它外层代码块的this。同时因为它没有this
,箭头函数不能作为构造函数使用,会抛出错误。