Javascript 为什么这个。勾号不是数字?
为什么此脚本中的this.tick不是数字Javascript 为什么这个。勾号不是数字?,javascript,Javascript,为什么此脚本中的this.tick不是数字 var universe; $(function() { universe = new Universe(); universe.timeStart(); }); function Universe() { this.timer = 0; this.tick = 0; this.timeStart = function(){ this.timer = setInterval(t
var universe;
$(function() {
universe = new Universe();
universe.timeStart();
});
function Universe() {
this.timer = 0;
this.tick = 0;
this.timeStart = function(){
this.timer = setInterval(this.timeForward, 500);
};
this.timeStop = function() {
clearInterval(this.timer);
};
this.timeForward = function(){
this.tick++;
console.log(this.tick);
};
}
因为您没有使用箭头函数来保留关键字this指向的执行上下文,所以一旦触发了进行setTimeout/setInterval调用的函数,这将是全局范围 如果在浏览器中运行此操作,则在解决超时/间隔时,此窗口将打开。您可以通过在代码中执行console.logthis来验证这一点 如果需要保持不变,请使用arrow函数确保在声明代码时,而不是在代码执行时,它始终指向它所指向的内容:setInterval=>this.timeForward,500 此外,现代浏览器支持现代JS,具有常量和类语法,因此您在函数中所做的工作可能更有意义:
class Universe() {
constructor() {
this.timer = 0;
this.tick = 0;
}
timeStart(){
this.timer = setInterval(() => this.timeForward(), 500);
}
timeStop() {
if (this.timer) {
clearInterval(this.timer);
}
}
timeForward() {
this.tick++;
console.log(this.tick);
}
}
const universe = new Universe();
universe.timeStart();
然后用a加载它,其中defer关键字的作用基本上与jQuery的$。。。是否:它仅在DOM完成后但在触发DOMContentLoaded之前运行文件中的代码,无论您在HTML中的何处放置该脚本标记。上下文问题。setInterval的函数参数不在Universe实例的上下文中调用。因为这在TimeOward中是指窗口,而不是您的objectChange to this.timer=setIntervalthis.timeForward.bindthis,500;或者使用箭头函数