繁体   English   中英

为什么箭头功能表现异常?

[英]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')创建的实例。


另请参见ES6箭头功能中的“ this”指的是什么? Arrow函数与函数声明/表达式:它们是否等效/可互换?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM