【发布时间】:2020-01-23 18:05:27
【问题描述】:
此示例按预期工作:
class A {
constructor(name) {
this.name = name
}
}
A.prototype.someMethod1 = function() { console.log("1: " + this.name) }
A.prototype.someMethod2 = function() { console.log("2: " + this.name) }
let a = new A("John")
a.someMethod1()
a.someMethod2()
有时我们需要将方法按其含义分组到子对象中,将其称为:a.some.method1()、a.some.method2()。让我们试着写:
class A {
constructor(name) {
this.name = name
}
}
A.prototype.some = {
method1: function() { console.log("1: " + this.name) },
method2: function() { console.log("2: " + this.name) }
}
现在我们可以调用 a.some.method1() 和 a.some.method2(),但是其中的“this”指向“a.some”,而不是根据需要指向“a”。因此,这些方法中的“this.name”现在将是“未定义的”。
那么我可以将方法的上下文绑定到主对象吗?
目前我只知道一种方法可以做到这一点。在构造函数中是这样的:
class A {
constructor(name) {
this._name = name
// bind context to this
Object.keys(this.name).forEach(n => {
this.name[n] = this.name[n].bind(this)
})
}
}
但是还有更优雅的方法吗?
注意:应在申报时指定。不接受修改 a.some.method1().call(a) 之类的方法调用。
【问题讨论】:
-
“有时我们需要将方法按其含义分组到子对象中” - 这背后的原因是什么?它们不都只是实例的方法吗?为什么需要这种分组?
-
例如,如果我有一种扩展某个类的插件,我不想让它们乱扔对象范围。我更喜欢一种方法,当每个插件都将其方法分开以插件名称命名的范围键时。我认为这不是唯一需要这样做的情况。
标签: javascript object methods binding this