【问题标题】:Difference between setinterval with an exist function and lambda expression for class in jsjs中类的setinterval与exist函数和lambda表达式的区别
【发布时间】:2021-12-01 07:04:05
【问题描述】:

我正在用 JavaScript 制作一个简单的游戏,你可以向敌人发射子弹。 实际上我没有任何问题,但是:

我为我的子弹创建了一个类,它有一个 Move 函数,我想为它设置一个间隔 但是当我像这样在构造函数中设置间隔时:

    setInterval(this.Move, 0);

我看到这个错误:

未捕获的类型错误:无法读取未定义的属性(读取“样式”) 在移动 (game.js:152)

但是当我这样设置和反转时:

    setInterval(() => {
        this.Move();
    }, 0);

它没有任何问题。

我只是想知道第一个有什么问题,我认为第二种方式,你正在做一个额外的事情(lambda 表达式)。

子弹类:https://i.stack.imgur.com/q23Lk.png

【问题讨论】:

    标签: javascript function oop setinterval bullet


    【解决方案1】:

    这是个好问题。关键区别在于箭头函数的使用。箭头函数旨在绑定到它们定义的范围。

    通过简单地将this.Move 传递给setIntervalsetInterval 将调用函数而不绑定到类/实例范围。

    下面的代码演示了将this.Move 传递给setInterval 的几种方法。有些有正确的范围,有些没有,希望这有助于您的理解。

    let outside_function = undefined;
    
    class X {
    
        constructor() {
            this.message = 'moving'
    
            // function is not bound to instance
            setInterval(this.move, 1000); // undefined
    
            // function is bound to instance
            setInterval(this.move.bind(this), 1000) // 'moving'
    
            // arrow function binds to 'this'
            setInterval(() => this.move(), 1000) // 'moving'
    
            // outside_function has no relationship with the class
            outside_function = this.move;
            setInterval(outside_function, 1000); // undefined
            setInterval(outside_function.bind(this), 1000) // 'moving'
        }
    
        move() {
            console.log(this.message)
        }
    }
    
    // also note that we can call the function like this
    // again, no class instance here
    X.prototype.move() // undefined
    
    new X();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多