Javascript 如何使倒计时可用于对象?
我有一个在点击事件中运行的倒计时。我需要使这个程序面向对象。我想用构造函数创建一个对象,这样我的倒计时就可以在我想要的每个div中运行。如果有人能告诉我如何使用构造函数创建一个clear对象,并在main.js文件中调用它,我就可以将目标div的id放入参数中 html 运行倒计时的jsJavascript 如何使倒计时可用于对象?,javascript,oop,Javascript,Oop,我有一个在点击事件中运行的倒计时。我需要使这个程序面向对象。我想用构造函数创建一个对象,这样我的倒计时就可以在我想要的每个div中运行。如果有人能告诉我如何使用构造函数创建一个clear对象,并在main.js文件中调用它,我就可以将目标div的id放入参数中 html 运行倒计时的js var timeout; function countdownto(target, time, callback) { var finish = new Date(time); var s
var timeout;
function countdownto(target, time, callback) {
var finish = new Date(time);
var s = 1000,
m = s * 60,
h = m * 60,
d = h * 24;
(function timer() {
var now = new Date();
var dist = finish - now;
var days = Math.floor(dist / d),
hours = Math.floor((dist % d) / h),
minutes = Math.floor((dist % h) / m),
seconds = Math.floor((dist % m) / s);
var timestring = minutes + ' minute(s) ' + seconds + ' seconde(s)';
target.innerHTML = timestring
clearTimeout(timeout);
if (dist > 0) {
timeout = setTimeout(timer, 1000);
} else {
callback()
}
})()
}
let runningBtn = document.getElementById("runningbutton")
runningBtn.addEventListener("click", function(e) {
clearTimeout(timeout);
// countdown element
var countdownel = document.getElementById('target');
// 20 min
var time = new Date()
time.setSeconds(time.getSeconds() + 1200)
// countdown function call
countdownto(countdownel, time, function() {
alert('finished');
})
})
在main.js中我想要什么
let newCountdown = new Countdown("target");
let newnewCountdown = new Countdown("targetbis");
对象由三部分组成:构造函数、成员方法和成员变量
// constructor
function Countdown(target,btn){
// member variable
this.target = target
this.btn = btn
this.btn.addEventListener("click", function(e) {
clearTimeout(timeout);
var time = new Date()
time.setSeconds(time.getSeconds() + 1200)
// countdown function call
this.countdownto(this.target, time, function() {
alert('finished');
})
})
}
// member method
Countdown.prototype.countdownto = function(){
...
}
在es6语法中,它看起来像:
class Point {
// constructor
constructor(x, y) {
// member variable
this.x = x;
this.y = y;
}
// member method
toString() {
return '(' + this.x + ', ' + this.y + ')';
}
}
只需将第二块代码包装到函数中。这是有关该网站的信息。虽然TBH,您调用的函数可能也一样好,是的,但是我希望在我的第一个代码(“js倒计时”)中使用类似“class Timer{constructor{}}”的对象,因为我的第二个(“运行倒计时的js”)正在另一个文件中运行,该文件已经是OOP对象,构造函数包含我的事件函数。请使用。代码基本上与我需要使用的类相同。因此,如果我对
类倒计时{constructor(target,btn){这里所有的“this”}这里的函数}
做同样的操作是否正确?类是es6的新语法。它有自己的结构,但oop是相同的。我将在答案中提供一个演示。@hugo这和一个类一样,只是一个例子
class Point {
// constructor
constructor(x, y) {
// member variable
this.x = x;
this.y = y;
}
// member method
toString() {
return '(' + this.x + ', ' + this.y + ')';
}
}