Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
267 views
in Technique[技术] by (71.8m points)

JavaScript Uncaught TypeError: this.calcTime is not a function

本人学生,写 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();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

除非使用箭头函数表示,否则这个this是运行时绑定的,绑定的是window而不是你的这个对象实例

要么用ES6的箭头函数去表示,这是定义时绑定的

要么手动在构造函数中用bind函数绑定this上下文


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...