gpt4 book ai didi

javascript - 为什么不能在 JavaScript "Class"中调用自身?

转载 作者:行者123 更新时间:2023-12-02 07:36:22 28 4
gpt4 key购买 nike

我不知道这段代码有什么问题。 Firefox 的错误控制台告诉我:“this.animateImgSlider 不是函数”。

我想用 jsItems[0].selectImage(0) 调用 this.selectImage() 然后让 this.animateImgSlider() 被调用多次直到 selfCall 为 false:

function WindowItem(inId) {
this.id = inId;
this.imgSliderTarget = 0;
this.imgSlider = document.getElementById("imgSlider"+inId);

this.animateImgSlider = function() {
var selfCall = true;
var currLeft = parseInt(this.imgSlider.style.left, 10);
if (currLeft < this.imgSliderTarget) {
currLeft += 8;
if (currLeft >= this.imgSliderTarget) {
currLeft = this.imgSliderTarget;
selfCall = false;
}
}
else {
currLeft -= 8;
if (currLeft <= this.imgSliderTarget) {
currLeft = this.imgSliderTarget;
selfCall = false;
}
}
this.imgSlider.style.left = currLeft+"px";
if (selfCall) setTimeout("this.animateImgSlider()", 0);
}

this.selectImage = function(inImg) {
this.imgSliderTarget = -inImg*488;
this.animateImgSlider();
}
}
var jsItems = new Array();
jsItems.push(new WindowItem(0));

这一行是抛出错误的那一行:

if (selfCall) setTimeout("this.animateImgSlider()", 0);

最佳答案

改用这个:

if (selfCall) {
var self = this;
setTimeout(function () {
self.animateImgSlider();
}, 0);
}

(当然,在顶部声明 self 并在整个函数中使用它而不是 this 对我来说更有意义)

传递给 setTimeout 以执行的字符串是在全局范围内执行的,这意味着 this 引用 window。它不在当前范围内执行,setTimeout 调用所在的范围。

附带说明,作为建议,我会将您的 animateImgSliderselectImage 方法移到外面,并移到 WindowItem 原型(prototype)中,所以它们可以被所有实例共享,而不是每次都创建一个新的匿名函数。因此,例如,您将:

function WindowItem(inId) {
// blah blah
}

WindowItem.prototype.animateImgSlider = function () {
// blah blah
};

WindowItem.prototype.selectImage = function(inImg) {
// blah blah
};

this 的值仍将引用特定实例,当然除非您尝试在 setTimeout 参数的字符串中使用它:)

这显然不是必需的,因为您的代码目前运行良好,但这是在构造函数上声明方法以供实例共享的常用约定。

关于javascript - 为什么不能在 JavaScript "Class"中调用自身?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15995427/

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