这个问题在这里已有答案:
下面的代码为Web组件内的html元素中的onchange
事件创建一个侦听器。它使用箭头功能。在这个函数中,我使用this
关键字来引用组件对象(类型为EulInstance
)。
class EulInstance extends HTMLElement {
constructor() {
super();
this.value = "Hi!";
}
...
async render() {
...
document.getElementById(selectId).onchange = evt => {
console.log("this:", this);
console.log("this.value:", this.value);
};
}
}
但this
指向另一个对象。在控制台中,我得到:
this:
+ <eul-instance edit="true" language="pt" types="["http://dbpedia.org/ontology/Provider" ..."
...
</div></eul-instance>
this.value: undefined
this
指向哪个对象?它具有EulInstance
Web组件的html文本,但不包含其字段。
新ECMAScript 6箭头函数中的this
关键字行为与旧的匿名函数(使用function(x) {...}
)不同。我的问题与How to access the correct this
inside a callback?不同。这个较老的问题说“ECMAScript 6引入了箭头函数,它可以被认为是lambda函数。它们没有自己的这种绑定。相反,它就像普通变量一样在范围内查找。”这是正确的,变量that
和this
,在下面的代码中,应该都指向EulInstance对象,但this
不指向。
...
async render() {
...
const that = this;
document.getElementById(selectId).onchange = evt => {
console.log("this:", this);
console.log("this.value:", this.value);
console.log(that === this); // Had to be true
};
}
箭头函数从其父级获取上下文(aka this
),因此箭头函数内的this
将与this
函数内的render()
相同。但是,这不一定是EulInstance:
const fn = (new EulInstance()).render;
fn(); // calls render with "this" being undefined
所以你应该检查你如何调用render()
...