gpt4 book ai didi

javascript - 为什么 'this' 在这种情况下不应该是这样?

转载 作者:行者123 更新时间:2023-11-28 20:31:33 25 4
gpt4 key购买 nike

我有一个在 Canvas 上使用的函数,我试图清除使用 .animate 函数调用的间隔,但是当我调用 .unbind(); 它仍然记录未定义,当它应该记录超时时,我不确定为什么它不起作用,也许你们可以帮忙

function Character(model, srcX, srcY, srcW, srcH, destX, destY, destW, destH) {
this.model = model;
this.srcX = srcX;
this.srcY = srcY;
this.srcW = srcW;
this.srcH = srcH;
this.destX = destX;
this.destY = destY;
this.destW = destW;
this.destH = destH;
this.timeout = undefined;

}

Character.prototype = {
draw: function() {
return ctx.drawImage(this.model, this.srcX, this.srcY, this.srcW, this.srcH,
this.destX, this.destY, this.destW, this.destH);
},

animate: function(claymation) {
var top = this; <<<<<--------Set the this variable
var queue = (function() {
var that = this;
var active = false;
if (!this.active) {
(function runQueue(i) {
that.active = true;
var length = claymation.length -1;
>>>>-Set the timeout top.timeout = setTimeout(function() {
claymation[i].action();
if ( i < length ) {
runQueue(i + 1);
if (i === length - 1) {
that.active = false;
}
}
}, claymation[i].time);
})(0);
}
})();
return queue;
},

update: function(callback) {
callback();
},
unbind: function() {
console.log(this.timeout); < Logs undefined
clearTimeout(this.timeout);
console.log(this.timeout); < Also logs undefined?
}
}

更新:

我正在调用解除绑定(bind):

player = new Character(playerModel, 0, 130, 100, 100, 150, 150, 100, 100)
if (e.which === 39) {
player.unbind();
key = undefined;
}

完整源代码:https://github.com/Gacnt/FirstGame/blob/master/public/javascripts/superGame.js#L50-L77

最佳答案

你的animate函数搞砸了。您已经看到需要存储 this reference在一个额外的变量(thattop,等等)中,因为它从一个调用到另一个调用,从一个函数到另一个函数,但你没有正确地做到这一点。

var top = this;
var queue = (function() {
var that = this;
var active = false;
if (!this.active) {
// use
that.active = true;
// or
top.timeout = …;
// or
that.active = false;
}
})();

虽然 top 是正确的并且将引用您调用该方法的 Character 实例,但 that 绝对不是 - 它将引用全局上下文 (window),这是正常(立即)调用的函数(表达式)中的默认 this 值。因此,this.active 几乎不会有值,并且您的 timeout 属性不会被设置。另请注意,IIFE 不会返回任何内容,因此queue 将是未定义

相反,您似乎想使用本地active 变量。那就去做吧!您不必使用一些类似于 Javathis 的关键字来引用“本地”变量 - 该变量只是作用域链中的下一个变量,因此将使用它。

我不太确定,但看起来你想要

Character.prototype.animate = function(claymation) {
var that = this; // variable pointing to context
var active = false; // again, simple local variable declaration
if (!active) {
(function runQueue(i) {
active = true; // use the variable
var length = claymation.length -1;
that.timeout = setTimeout(function() { // use property of "outer" context
claymation[i].action();
if ( i < length ) {
runQueue(i + 1);
if (i + 1 === length) {
active = false; // variable, again!
}
}
}, claymation[i].time);
})(0);
}
};

关于javascript - 为什么 'this' 在这种情况下不应该是这样?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16269092/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com