This question has already been answered:
- Loss of context call 5 responses
var user = { name: 'Иван', age: 16, runUpAge: function () { setInterval(function () { this.age = ++this.age; console.log(this.age); }, 1000); } } user.runUpAge(); This question has already been answered:
var user = { name: 'Иван', age: 16, runUpAge: function () { setInterval(function () { this.age = ++this.age; console.log(this.age); }, 1000); } } user.runUpAge(); A similar question was asked earlier and an answer has already been received. If the answers provided are not exhaustive, please ask a new question .
Let me guess, you want the runUpAge function runUpAge change the age field of the object, but it does not change, besides, it can throw errors at all.
Why so? Because you are using setInterval and an anonymous function that does not save a reference to this . Solutions two
1) Old
var user = { name: 'Иван', age: 16, runUpAge: function () { var self = this; // руками сохраняем ссылку setInterval(function () { self.age = ++self.age; console.log(self.age); }, 1000); } } user.runUpAge(); 2) Fashionable, new In the es6 specification, we have introduced arrow functions that retain a link to this this , in the context of which they were created
var user = { name: 'Иван', age: 16, runUpAge: function () { setInterval(() => { this.age = ++this.age; console.log(this.age); }, 1000); } } user.runUpAge(); Source: https://ru.stackoverflow.com/questions/602757/
All Articles