[英]Why arrow function is behaving weirdly?
考虑以下代码:
function Person (name) {
this.name = name;
this.showName = function() { console.log(name, this.name);}
}
var foo = new Person('foo');
var bar = new Person('bar');
foo.showName = bar.showName;
foo.showName(); // prints "bar foo"
可以预期,因为它仍然绑定“ foo”。
现在具有箭头功能:
function Person (name) {
this.name = name;
this.showName = () => console.log(name, this.name);
}
var foo = new Person('foo');
var bar = new Person('bar');
foo.showName = bar.showName;
foo.showName(); // prints "bar bar"
我知道'this'不会绑定到箭头功能。 但是,此处的“ foo”上下文在showName()中已更改。 这本身消除了“绑定”功能的一个用例。 它背后的原因是什么?
在箭头函数内部, this
是按词法解析的,基本上像其他变量一样,例如name
。 函数的调用方式无关紧要, this
值将在创建函数时确定。
因此, this
bar.showName
内部bar.showName
将引用由new Person('bar')
创建的实例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.