admin管理员组文章数量:1425665
my object has a function that i want to call recurseively. my problem is how do i use setTimeout to point to the method of that instance of the object?
MyObject.prototype.Play = function() {
// do some stuff
setTimeout(thecurrentmethodnameHERE, 1000);
}
var test = new MyObject();
test.Play();
my object has a function that i want to call recurseively. my problem is how do i use setTimeout to point to the method of that instance of the object?
MyObject.prototype.Play = function() {
// do some stuff
setTimeout(thecurrentmethodnameHERE, 1000);
}
var test = new MyObject();
test.Play();
Share
Improve this question
edited Nov 2, 2009 at 20:46
Will
asked Nov 2, 2009 at 20:40
WillWill
1,6224 gold badges25 silver badges39 bronze badges
2 Answers
Reset to default 7Just do setTimeout(this.someMethod, 1000)
, but keep in mind that it will be called in a global context, so any reference to this
inside someMethod
will be window
, assuming a web browser.
You can do it like this in your constructor, if that's an issue:
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);
};
Some libraries define Function.prototype.bind
which you can use in these situations, setTimeout(this.someMethod.bind(this), 1000)
, which simply returns a new function that gets call()
ed with your desired object as this
, it's a nice, simple function that you can implement without messing with the Function
prototype too.
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);
}
本文标签: JavaScript object method name for setTimeoutStack Overflow
版权声明:本文标题:JavaScript object method name for setTimeout - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745450703a2658869.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论