我遵循了tutorial来创建JavaScript秒表,并试图将其扩展为与多个秒表(一个类的多个实例)一起使用。我遇到的问题是,当我试图在时钟滴答声中显示当前值时,我需要使用“ this”对类实例进行硬编码,这是行不通的(在我使用console.log的那一行中)。我已将代码缩减到最低限度以尝试理解此方面,并粘贴了以下内容:
function Timer(){
var time1 = null;
var time2 = null;
var timeLoop = null;
function getTime(){
var day = new Date();
return day.getTime();
}
this.start = function(){
time1 = getTime();
timeLoop = setInterval(function(){
time2 = getTime();
console.log(_Timer.duration());
//console.log(this.duration());
},500);
}
this.duration = function(){
return (time1 - time2) / 1000;
}
}
我认为以下链接描述了我的问题,但我对它的理解不够,无法在此处应用它。问题是由于所有者是this.start而不是仅此而引起的,我如何修改代码以使其可与Timer的任何实例一起使用?
http://www.quirksmode.org/js/this.html
我同时包含了硬编码值行和行不通的“ this”行。
谢谢,
杰伦
如果要使this
属性保持一致,则应绑定所调用的函数。
例如,
setInterval(function() { /* code here */ }.bind(this), 500)
这样,内部函数的this
将与外部函数的function
相同。
[每当看到this
时,您都可以假定this
的值发生了变化,因此间隔window
中的回调函数实际上是this
,而不是对象。
简单的解决方案是只将function Timer(){
var time1 = null;
var time2 = null;
var timeLoop = null;
function getTime(){
var day = new Date();
return day.getTime();
}
this.start = function(){
var self = this;
time1 = getTime();
timeLoop = setInterval(function(){
time2 = getTime();
console.log(self.duration());
},500);
}
this.duration = function(){
return (time1 - time2) / 1000;
}
}
存储在变量中
this
this.start = function(){
var self = this;
time1 = getTime();
timeLoop = setInterval(function(){
time2 = getTime();
console.log(self.duration());
},500);
}
不是局部变量,因此不会保存在闭包中。您需要分配一个局部变量:
function Timer(){
var time1 = null;
var time2 = null;
var timeLoop = null;
var _this = this;
function getTime(){
var day = new Date();
return day.getTime();
}
this.start = function(){
time1 = getTime();
timeLoop = setInterval(function(){
time2 = getTime();
console.log(_this.duration());
},500);
}
this.duration = function(){
return (time1 - time2) / 1000;
}
}
尝试:
function Timer(){
var time1 = null;
var time2 = null;
var timeLoop = null;
}
Timer.prototype.getTime = function(){
var day = new Date();
return day.getTime();
}
Timer.prototype.start = function(){
time1 = this.getTime();
timeLoop = this.setInterval(function(){
time2 = this.getTime();
console.log(this.duration());
}.bind(this),500);
}
Timer.prototype.duration = function(){
return (time1 - time2) / 1000;
}
第一件事。 Javascript不支持基于类的OOP。它是OOP,它的继承是原型。
以下是如何通过计时器示例实现原型OOP功能的示例:
MDN's Javscript Reintroduction
查看bind
的“自定义对象”部分
在您的教程中显示的方式没有错。只是这是一种更干净的方法,并且console.log
调用仅对于this
语句才需要,否则它将window
与bind
关联。如果您删除它,也可以删除bind(this)
。
使用bind(this)
效果很好。
var timer = {
start: function() {
setInterval(function() {console.log(this.duration());}.bind(this), 1000);
}
}
timer.start();
但是如果您将const
与箭头功能一起使用,则可能没有必要:
const