好吧,我有了这个原型(prototype)对象 Stage,它的每个部分都可以工作,除了这个递归调用。
Stage.prototype.start = function(key) {
//var maxScrollLeft = document.getElementById("content").scrollWidth;
$content.scrollLeft($content.scrollLeft() + this.initspeed);
if(key < this.maxScrollLeft || key > 0) {
setTimeout(function() {
this.start(key+2);
},1);
}else{
console.log("stop");
}
}
我正在努力使 Stage.prototype.start 在此 if 语句中被调用,使用 this.start();但是我总是得到
未捕获的 TypeError:对象 [object global] 没有方法“开始”
我认为这与匿名函数中的调用有关,关于如何解决这个问题有什么想法吗?
最佳答案
this
在 setTimeout 的匿名回调中指向全局对象,因为该函数未绑定(bind)到任何地方,所以它被提升到全局范围。在这种情况下,您的回调是从 window
(浏览器)或 global
(节点等)上下文执行的,因此 this
指向全局范围,因为该函数是从该上下文中调用的。有很多方法可以解决这个问题。一种简单的方法是将 this
缓存到一个变量中,然后在回调函数中使用它。
Stage.prototype.start = function(key) {
var self = this; //cache this here
//var maxScrollLeft = document.getElementById("content").scrollWidth;
$content.scrollLeft($content.scrollLeft() + this.initspeed);
if(key < this.maxScrollLeft || key > 0) {
setTimeout(function() {
self.start(key+2); //use it to make the call
},1);
}else{
console.log("stop");
}
}
另一种方法是使用 function.prototype.bind 绑定(bind)上下文.
Stage.prototype.start = function(key) {
//var maxScrollLeft = document.getElementById("content").scrollWidth;
$content.scrollLeft($content.scrollLeft() + this.initspeed);
if(key < this.maxScrollLeft || key > 0) {
setTimeout((function() {
this.start(key+2); //now you get this as your object of type stage
}).bind(this),1); //bind this here
}else{
console.log("stop");
}
}
关于javascript - 原型(prototype)函数内的递归调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18994712/