【发布时间】:2012-03-06 17:31:17
【问题描述】:
在正确的 Javascript 中进一步进行实验,我正在尝试从另一种方法 (WaitAndSayHello) 运行一种方法 (SayHello)。由于涉及回调,我使用了bind 来确保每个方法中的“this”都指向对象。
pretendThingConstructor = function (greeting) {
this.greeting = greeting;
this.SayHello = function() {
console.log(this.greeting); // Works
};
this.WaitAndSayHello = function() {
setTimeout(function() {
console.log(this)
this.SayHello() // Fails
}, 500);
}
this.WaitAndSayHello.bind(this); // This bind() doesn't seem to work
}
var pretend_thing = new pretendThingConstructor('hello world');
pretend_thing.SayHello();
pretend_thing.WaitAndSayHello();
代码打印'hello world',然后第二次失败并显示'Object # has no method 'SayHello''。我可以从 console.log 中看到,“this”指的是事件。但是不应该使用 bind() 解决这个问题吗?
我怎样才能使 bind() 工作?
此外,我想干净利落地这样做:即,不要在多个地方引用对象的名称。
【问题讨论】:
标签: javascript oop methods bind