我正在尝试将以下函数转换为 JavaScript 中的类(原始函数来自CMS https://stackoverflow.com/users/5445/cms已创建here https://stackoverflow.com/a/1192001/177416),
function Countdown(options) {
var timer,
instance = this,
seconds = options.seconds || 10,
updateStatus = options.onUpdateStatus || function () {},
counterEnd = options.onCounterEnd || function () {};
function decrementCounter() {
updateStatus(seconds);
if (seconds === 0) {
counterEnd();
instance.stop();
}
seconds--;
}
this.start = function () {
clearInterval(timer);
timer = 0;
seconds = options.seconds;
timer = setInterval(decrementCounter, 1000);
};
this.stop = function () {
clearInterval(timer);
};
}
通过这种用法,
var myCounter = new Countdown({
seconds:5, // number of seconds to count down
onUpdateStatus: function(sec){console.log(sec);}, // callback for each second
onCounterEnd: function(){ alert('counter ended!');} // final action
});
myCounter.start();
我的尝试是,
Countdown: class {
constructor(options) {
this.seconds = options.seconds || 10;
this.updateStatus = options.onUpdateStatus || function () { };
this.counterEnd = options.onCounterEnd || function () { };
this.instance = this;
this.timer = null;
}
decrementCounter() {
this.updateStatus(this.seconds);
if (this.seconds === 0) {
this.counterEnd();
this.instance.stop();
}
this.seconds--;
}
start() {
clearInterval(this.timer);
this.timer = 0;
this.timer = setInterval(this.decrementCounter, 1000);
}
stop () {
clearInterval(this.timer);
}
}
并这样称呼它,
var counter = new Countdown({
seconds:5, // number of seconds to count down
onUpdateStatus: function(sec) {
$("#timer").text(sec);
}, // callback for each second
onCounterEnd: function() {
closeModal();
} // final action
});
counter.start();
它抛出这个错误decrementCounter()
,
未捕获的类型错误:this.updateStatus 不是函数
我究竟做错了什么?