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(); 

Reported as a duplicate at Grundy. javascript 12 Dec '16 at 18:46 .

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 .

  • The essence of the issue is not clear. Can be more specific? - Yuri

1 answer 1

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(); 
  • Yes . Thank you kind man - Anon
  • @Anon, mark the answer as correct if it suits you - ThisMan
  • There are two solutions - there are a little more solutions :) - Grundy