【问题标题】:ES6: How may one reference an instance method bound to "this"?ES6:如何引用绑定到“this”的实例方法?
【发布时间】:2014-08-06 21:55:59
【问题描述】:

取下面的 ES6 代码:

class MyClass {
    constructor() {
        this.attribute = 'test'
    }

    myMethod() {
        console.log(this.attribute)
    }
}

// works - prints 'test'
var instance = MyClass()
instance.myMethod()

// doesn't work - outputs "undefined".  "this" isn't bound to the function.
var methodRef = instance.myMethod
methodRef()

最初,我预计第二个示例会将“this”绑定到该方法,但经过思考,如果instance.method(arg)method(instance, arg) 的语法糖,这是有道理的。首先 - 它只是语法糖吗?在 ES5 中,大多数“类”实现都没有这个问题。其次,有没有办法实现我想要做的事情?

注意:我使用的是es6-transpiler,这可能有问题。

【问题讨论】:

    标签: javascript methods binding ecmascript-6


    【解决方案1】:

    我认为javascript没有绑定方法的概念,这意味着methodRef与实例无关。

    所以:

    instance.myMethod() 等价于methodRef.call(instance)

    methodRef() 等价于methodRef.call()

    我想你要找的是:var methodRef = instance.myMethod.bind(instance)

    【讨论】:

      猜你喜欢
      • 2015-11-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多