[英]Difference between setinterval with an exist function and lambda expression for class in js
I'm making a simple game with javascript that you can fire bullet to enemies.我正在用javascript制作一个简单的游戏,你可以向敌人发射子弹。 Actually I don't have any problem making it but:实际上我没有任何问题,但是:
I made a class for my bullets that it has a Move function and I want to set an interval for it but when I set an interval in my constructor like this:我为我的子弹创建了一个类,它有一个Move函数,我想为它设置一个间隔,但是当我在我的构造函数中设置一个间隔时,如下所示:
setInterval(this.Move, 0);
I see this error:我看到这个错误:
uncaught TypeError: Cannot read properties of undefined (reading 'style') at Move (game.js:152)未捕获的类型错误:无法在移动 (game.js:152) 时读取未定义的属性(读取“样式”)
But when I set and inverval like this:但是当我像这样设置和反转时:
setInterval(() => {
this.Move();
}, 0);
It works without any problem.它可以毫无问题地工作。
I just what to know what is wrong with first one, I think the second way, you're making an extra thing (lambda expression).我只是想知道第一个有什么问题,我认为第二种方式,你正在做一个额外的事情(lambda 表达式)。
Bullet Class: https://i.stack.imgur.com/q23Lk.png子弹类: https : //i.stack.imgur.com/q23Lk.png
It's a good question.这是个好问题。 The key difference is the use of the arrow function.主要区别在于箭头函数的使用。 Arrow functions are designed to bind to the scope that they are defined in.箭头函数旨在绑定到定义它们的作用域。
By simply passing this.Move
to setInterval
, setInterval
will invoke the function without binding to the class/instance scope.通过简单地将this.Move
传递给setInterval
, setInterval
将调用该函数而不绑定到类/实例范围。
The code below demonstrates several ways you could have passed this.Move
to setInterval
.下面的代码演示了几种可以将this.Move
传递给setInterval
。 Some have the correct scope, some don't, hopefully this will help your understanding.有些有正确的范围,有些没有,希望这能帮助您理解。
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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.