脚本宝典收集整理的这篇文章主要介绍了箭头函数中this的指向问题,脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
箭头函数中this指向等
“箭头函数”的this
,总是指向定义时所在的对象,而不是运行时所在的对象。
-
箭头函数位于foo
函数内部。只有foo
函数运行后(被调用后,内部this确定),它才会按照定义生成,所以foo
运行时所在的对象,恰好是箭头函数定义时所在的对象
function foo() {
setTimeout( () => {
console.log("id:", this.id);
},100);
}
var id = 21; // 箭头函数运行时所在的环境
foo.call( { id: 42 } ); // 箭头函数定义时所在的环境
// 结果是 id: 42
function foo() {
return () => {
return () => {
return () => {
console.log("id:", this.id);
};
};
};
}
var f = foo.call({id: 1});
var t1 = f.call({id: 2})()();
var t2 = f().call({id: 3})();
var t3 = f()().call({id: 4});
// 结果是: 1,1,1
var obj = {
field: 'hello',
getField: () => {
// 此时箭头函数被定义,this指向obj的this,而obj的this是window,则此箭头函数的this指向window
console.log(this)
},
}
obj.getField();
//window
-
箭头函数里不但没有 this,也没有 arguments, super ……
var arguments = 42;
var arr = () => arguments;
arr(); // 42
function foo() {
var f = (i) => arguments[0]+i;
// foo函数的间接参数绑定
return f(2);
}
foo(1); // 3
var f = (i) => arguments;
f(1); // arguments is not defined
-
通过 call 或 apply 调用: 由于 this
已经在词法层面完成了绑定,通过 call()
或 apply()
方法调用一个函数时,只是传入了参数而已,对 this
并没有什么影响
var adder = {
base : 1,
add : function(a) {
var f = v => v + this.base;
return f(a);
},
addThruCall: function(a) {
var f = v => v + this.base;
var b = {
base : 2
};
return f.call(b, a);
}
};
console.log(adder.add(1)); // 输出 2
console.log(adder.addThruCall(1)); // 仍然输出 2
-
箭头函数不能用作构造器,和 new
一起用会抛出错误。
var Foo = () => {};
var foo = new Foo(); // TypeError: Foo is not a constructor
-
箭头函数没有prototype
属性。
var Foo = () => {};
console.log(Foo.prototype); // undefined
-
yield
关键字通常不能在箭头函数中使用(除非是嵌套在允许使用的函数内)。因此,箭头函数不能用作生成器。
参考资料
以上是脚本宝典为你收集整理的箭头函数中this的指向问题全部内容,希望文章能够帮你解决箭头函数中this的指向问题所遇到的问题。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。