'this'不引用函数内部的es6对象

时间:2019-04-04 11:32:04

标签: javascript node.js ecmascript-6 es6-class

snake.js中有一个es6类'Snake'

我有一个index.js

index.js实例化一个“蛇”

index.js调用snake.move(dir)

我收到一个错误this.isProperDir is not a function

snake.js

    isProperDir(dir) {
        dir = dir.toLowerCase();
        var arr = ['left', 'up', 'down', 'right'];
        return arr.includes(dir);
    }

    move(dir) {
        console.log('a2: ' + this);
        console.log('d: ' + this.isProperDir(dir));
    }

index.js

window.setInterval(snake.move, 1000);

这将打印到控制台:

a2: [object Window]

Uncaught TypeError: this.isProperDir is not a function

我只想在我的es6类中调用该函数,我想写this将引用该类中的函数,但它似乎会引发错误。

0 个答案:

没有答案
相关问题