我的對象有一個我想要調用的函數。 我的問題是我如何使用setTimeout指向該對象的實例的方法?setTimeout的JavaScript對象方法名稱
MyObject.prototype.Play = function() {
// do some stuff
setTimeout(thecurrentmethodnameHERE, 1000);
}
var test = new MyObject();
test.Play();
我的對象有一個我想要調用的函數。 我的問題是我如何使用setTimeout指向該對象的實例的方法?setTimeout的JavaScript對象方法名稱
MyObject.prototype.Play = function() {
// do some stuff
setTimeout(thecurrentmethodnameHERE, 1000);
}
var test = new MyObject();
test.Play();
只是做setTimeout(this.someMethod, 1000)
,但請記住,這將在全球範圍內被調用,所以this
內someMethod
任何引用將window
,假設一個網頁瀏覽器。
你可以像下面這樣做在你的構造,如果這是一個問題:
YourObject = function(name) {
var self = this;
self.name = name;
self.someMethod = function() {
alert(self.name); // this.name would have been window.name
};
setTimeout(self.someMethod, 1000);
};
有些庫定義Function.prototype.bind
,你可以在這些情況下使用,setTimeout(this.someMethod.bind(this), 1000)
,它只是返回一個新功能得到call()
版與您想要的對象this
,這是一個很好的,簡單的功能,你可以實現而不會搞亂Function
原型。
Function.prototype.bind = function(scope) {
var _function = this;
return function() {
return _function.apply(scope, arguments);
}
}
MyObject.prototype.Play = function() {
// do some stuff
setTimeout(thecurrentmethodnameHERE.bind(this), 1000);
}
freakin nlogax,你在這裏做什麼! – 2009-11-02 20:50:10