我有一个构造函数,它注册一个事件处理程序:
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 Student
{
name = "John";
sayHello()
{
console.log("Hi, I'm " + this.name);
}
}
Run Code Online (Sandbox Code Playgroud)
它由TypeScript编译器编译为:
var Student = (function () {
function Student() {
this.name = "John";
}
Student.prototype.sayHello = function () {
console.log("Hi, I'm " + this.name); //here is the problem. Accessing name via this
};
return Student;
})();
Run Code Online (Sandbox Code Playgroud)
现在,如果我创建一个对象并调用一个方法,一切正常.
var student = new Student();
student.sayHello(); //prints Hi, I'm John
Run Code Online (Sandbox Code Playgroud)
但是如果我从回调中调用该方法,它就会中断(this正如预期的那样引用一个Window)
setTimeout(student.sayHello); //prints Hi, I'm
Run Code Online (Sandbox Code Playgroud)
我知道thisJavaScript和C#或Java 之间的区别.我也知道,TypeScript试图解决这个差异.例如这段代码:
class Student
{
name = "John"; …Run Code Online (Sandbox Code Playgroud)