我有一个构造函数,它注册一个事件处理程序:
function MyConstructor(data, transport) {
this.data = data;
transport.on('data', function () {
alert(this.data);
});
}
// Mock transport object
var transport = {
on: function(event, callback) {
setTimeout(callback, 1000);
}
};
// called as
var obj = new MyConstructor('foo', transport);Run Code Online (Sandbox Code Playgroud)
但是,我无法data在回调中访问已创建对象的属性.它看起来this并不是指创建的对象,而是指另一个对象.
我还尝试使用对象方法而不是匿名函数:
function MyConstructor(data, transport) {
this.data = data;
transport.on('data', this.alert);
}
MyConstructor.prototype.alert = function() {
alert(this.name);
};
Run Code Online (Sandbox Code Playgroud)
但它表现出同样的问题.
如何访问正确的对象?
我厌倦了编写这样的代码:
class Something {
constructor() {
this.method = this.method.bind(this);
this.anotherOne = this.anotherOne.bind(this);
// ...
}
}
Run Code Online (Sandbox Code Playgroud)
很费时间,而且很容易忘记绑定一个方法。我知道 class fields 提案,但它仍然是第 3 阶段,似乎有一些问题。
我当前的解决方案(基于此答案)如下所示:
class Something {
constructor() {
// Get all defined class methods
const methods = Object.getOwnPropertyNames(Object.getPrototypeOf(this));
// Bind all methods
methods
.filter(method => (method !== 'constructor'))
.forEach((method) => { this[method] = this[method].bind(this); });
}
}
Run Code Online (Sandbox Code Playgroud)
这似乎有效,但我想知道是否有更好的方法,或者此方法是否存在我不知道的问题。
我遇到的问题是,如果我没有在构造函数中绑定我的类函数,我必须记住以后“正确地”调用它们。例如:
const classInstance = new Something();
// This fails for a non-obvious reason
someAction()
.then(classInstance.method);
// This …Run Code Online (Sandbox Code Playgroud) 我有这个JavaScript代码:
var b = document.getElementById("b");
function A() {
this.f = "1";
}
A.prototype.t = function() {
b.innerHTML = this.f;
};
var a = new A();
var l = a.t;
l();
Run Code Online (Sandbox Code Playgroud)
this当我试着打电话时为什么未定义?如何在不过度冗长或存储太多的情况下恢复该上下文?