es6 - JavaScript Uncaught TypeError: this.calcTime is not a function
阿神
阿神 2017-04-11 12:24:40
[JavaScript讨论组]

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

闭关修行中......

全部回复(1)
高洛峰

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

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

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

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号