This question has already been answered:

It is necessary that the function continue to work in its context:

function aaaa(v) { this.n = v; this.inscr = function() { this.n++; } this.bbbb = function(v) { var self = this; console.log(this.n); aaaa(5).inscr(); console.log(self.n); } return this; } aaaa(1).bbbb(); 

It is necessary that the second console.log (self.n) continue to work in its own context. That is, the first and second console.log should output the same result. Is it possible to do without "new"?

Reported as a duplicate at Grundy. javascript Dec 1 '16 at 18:50 .

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 .

  • You understand, of course, that in your code all this is this window ? "must output the same result" - which one? - Igor
  • @Igor first console result - bsbak

2 answers 2

 function aaaa(v) { var result = {}; result.n = v; result.inscr = function() { this.n++; } result.bbbb = function(v) { var self = this; console.log(this.n); aaaa(5).inscr(); console.log(self.n); } return result; } aaaa(1).bbbb(); 

    In the call aaaa(1) this set to window (in strict mode it is undefined , there would be victims :)).
    That is, the body adds 3 variables for the window (a number and two functions) and returns the window .
    Next, the window bbbb() method is called, which for some reason saves this to self (saving the context is necessary when it is lost, the context is not lost in the body of window.bbbb );
    displays window.n (which is 1 after setting to aaaa(1) );
    then the methods are overwritten by their copies, but with the new value of window.n , which is now 5 , inscr() obviously increments window.n (now it is 6 );
    new value is displayed.

    A quite suitable solution is in the response of the user @Igor , I will duplicate it:

     function aaaa(v) { var result = {}; result.n = v; result.inscr = function() { this.n++; } result.bbbb = function(v) { var self = this; console.log(this.n); aaaa(5).inscr(); console.log(self.n); } return result; } aaaa(1).bbbb(); 

    Every new call to aaaa creates a new object with individual parameters (perhaps the functions refer to one object, I don’t know for sure).

    • "every new call aaaa creates a new object" - I know for sure :) - Igor
    • @Igor, you know something, but the vehicle may not know. - user207618