在Javascript中,箭头函数侦听器指向哪个对象的`this`关键字? [重复]

问题描述 投票:0回答:1

这个问题在这里已有答案:

下面的代码为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="[&quot;http://dbpedia.org/ontology/Provider&quot; ..."
...
</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函数。它们没有自己的这种绑定。相反,它就像普通变量一样在范围内查找。”这是正确的,变量thatthis,在下面的代码中,应该都指向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
        };
   }
javascript this listener web-component arrow-functions
1个回答
0
投票

箭头函数从其父级获取上下文(aka this),因此箭头函数内的this将与this函数内的render()相同。但是,这不一定是EulInstance:

 const fn = (new EulInstance()).render;
 fn(); // calls render with "this" being undefined

所以你应该检查你如何调用render() ...

© www.soinside.com 2019 - 2024. All rights reserved.