es6 - JavaScript Uncaught TypeError: this.calcTime is not a function

查看:79
本文介绍了es6 - 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();

解决方案

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

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

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

这篇关于es6 - JavaScript Uncaught TypeError: this.calcTime is not a function的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆