gpt4 book ai didi

JavaScript 类方法

转载 作者:行者123 更新时间:2023-11-30 08:14:14 24 4
gpt4 key购买 nike

我这样定义我的类:

function Slot(slot, maxSpeed, timer) {
this.slot = slot;
this.speed = 0;
this.maxSpeed = maxSpeed;
this.timer = timer;
this.interval = null;

this.go = function() {
var $slot = $(this.slot);
console.log(this.slot);
$slot.addClass('motion');
$slot.spStart();

this.interval = window.setInterval(function() {
var step = Math.floor(Math.random() * ((this.speed / 100) * 25)) + 1;
if (this.speed < (this.maxSpeed / 2)) {
this.speed += step;
}

if (this.speed >= (this.maxSpeed / 2)) {
this.speed -= step;
}
console.log(this.slot);
$slot.spSpeed(this.speed);
}, timer);
};

$(this.slot).pan({ fps: '30', dir: 'down' });
$(this.slot).spStop();
}

第一个 console.log 返回预期值,但是一旦我进入 setInterval 函数,所有变量(this.slot、this.speed)都未定义?虽然我还在他们的范围之内……

最佳答案

在 Javascript 中习惯范围有点奇怪,当您开始使用 setInterval 和 setTimeout 时甚至更奇怪。

在您的例子中,区间内的 this 是指匿名函数本身。您可以将“this”分配给匿名函数之外的另一个变量:

var self = this;
this.interval = window.setInterval(function(){ /* use self here instead of this*/}

或者您可以在间隔步骤中调用对象上的函数:

this.interval = window.setInterval(this.callback, timer);

关于JavaScript 类方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6294516/

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