javascript - ES6 中类的引用丢失

标签 javascript ecmascript-6 class-reference

<分区>

我有以下结构 Javacript es5-es6 并且 Controller 类在 Get 类中丢失了引用,我已经在调查但我找不到如何避免丢失引用。

class Controller {
    constructor() {
        this.name = 'Test';
    }
    test() {
        console.log(1, this.name);
    }
}

referenceController = new Controller();
// working reference: console.log(1, 'Test');
referenceController.test();


class Get {
    method() {
        return {
            controller: referenceController.test
        }
    }
}

// Lost self reference: console.log(1, undefined)
new Get().method().controller() 

最佳答案

在本节中,您将测试函数添加为返回对象的属性。

{
    controller: referenceController.test
}

然后,当您将它作为该对象的方法调用时 (method().controller()) this 引用该对象,而 name 从对象中读取属性。

您可以绑定(bind)上下文以保留引用:

referenceController.test.bind(referenceController)

关于javascript - ES6 中类的引用丢失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43106224/

相关文章:

javascript - AngularJS 中过滤器的未定义参数

javascript - 如何从同一对象的方法引用属性?

javascript - 无法安装 jQuery 1.11.3

javascript - 如何从 ES6 类中创建迭代器

javascript - 将状态传递给 preact 组件

delphi - 测试类引用(元类)变量中的类是否为 TMyClass

javascript - 加载 YouTube 评论后火狐插件自动调用 JavaScript

Delphi 类引用...又名元类...何时使用它们

Objective-c,如何从另一个类访问实例变量

javascript - 为什么 'await' 在 '.then()' 函数返回的代理上触发 'async'?