本人学生,写 JS 倒计时作业,代码 this.calcTime();
在执行的时候遇到错误:
Uncaught TypeError: this.calcTime is not a function
贴出写的代码,写的不好请见谅,使用了 ESLint :
/* eslint linebreak-style: ["error", "windows"] */
/**
* Countdown class.
* @class Countdown
*/
class Countdown {
/**
* Creates an instance of Countdown.
* @param {Date} countDate
* @memberOf Countdown
*/
constructor(countDate) {
this.countDate = new Date(countDate);
}
/**
* Calculator time method.
* @memberOf Countdown
*/
calcTime() {
let _nowTime = new Date().getTime();
let _milliSeconds = this.countDate.getTime() - _nowTime;
this._seconds = _milliSeconds / 1000;
this._minutes = this._seconds / 60;
this._hours = this._minutes / 60;
this._days = this._hours / 24;
}
/**
* Remainder time method.
* @param {number} time
* @param {number} remainder
* @return {number} Result of a time remainder
* @memberOf Countdown
*/
timeRemainder(time, remainder) {
return time % remainder;
}
/**
* Math.floor() time.
* @param {number} time
* @return {number}
* @memberOf Countdown
*/
timeFloor(time) {
return Math.floor(time);
}
/**
* Start countdown time.
* @memberOf Countdown
*/
start() {
// console.log(this);
this.calcTime();
let _second = this.timeFloor(this.timeRemainder(this._seconds, 60));
let _minute = this.timeFloor(this.timeRemainder(this._minutes, 60));
let _hour = this.timeFloor(this.timeRemainder(this._hours, 24));
let _day = this.timeFloor(this._days);
$('second').html(_second);
$('minute').html(_minute);
$('hour').html(_hour);
$('day').html(_day);
setTimeout(this.start, 1000);
}
}
let countdown = new Countdown('01/01/2018');
window.onload = countdown.start();
除非使用箭头函数表示,否则这个this是运行时绑定的,绑定的是window而不是你的这个对象实例
要么用ES6的箭头函数去表示,这是定义时绑定的
要么手动在构造函数中用bind函数绑定this上下文