An object method loses its scope when called with setInterval

Is there a way to print the value of an array players, as in the example below? I tried to find a solution in a few hours ...

function Room(name, id, owner) {
    this.players = [];
    this.movementz =  function() {
        console.log(this.players);
    }
}

I call the function with setIntervalfor example:

setInterval(room.movementz, 1000);
+4
source share
1 answer

The problem here is that the object this: creating your object and calling it manually movementzwill work, because the element thisis the object itself, but with the help setIntervalwill lead to a method for calling withthis === window .

Here is an example:

var room = new Room();

room.movementz(); // []
setInterval(room.movementz, 1000); // undefined

, , movementz setInterval, this window, , , , room this. bind, :

var room = new Room(),
    players = "hello";

setInterval(room.movementz, 1000);
// this will output "hello" because this === window

setInterval(room.movementz.bind(room), 1000);
// this will output [], because now this === room
+5

Source: https://habr.com/ru/post/1568826/


All Articles