Do I understand correctly that this example uses the same object, a new one is not created?

var OneInstance = function(numberAdd) { if(this.numbers === undefined) this.numbers = []; this.numbers.push(numberAdd); this.showNumbers = function() { alert(this.numbers); } return this; } OneInstance(1).showNumbers(); OneInstance(1).showNumbers(); 

Jsfiddle

    2 answers 2

    Yes, this object is the same - window :

     var OneInstance = function(numberAdd) { if (this.numbers === undefined) this.numbers = []; this.numbers.push(numberAdd); this.showNumbers = function() { console.log(this.numbers); } return this; } OneInstance(1).showNumbers(); OneInstance(2).showNumbers(); window.showNumbers(); 

    PS - explain what you want. The impression is that you have somewhere missing the new operator.

      If the function is called in the global scope, then this means a reference to the browser object window That is, the context object is the window object.

      When the function is first called, the numbers property is added to the window object.

       if(this.numbers === undefined) this.numbers = []; ^^^^^^^^^^^^^^^^^^^^^^^^^^ 

      And also with each call, the windows showNumbers property is showNumbers

        this.showNumbers = function() { console.log(this.numbers); } 

      In these calls

       OneInstance(1).showNumbers(); OneInstance(2).showNumbers(); 

      since the OneInstance function returns this , it returns a reference to the window object, and its showNumbers property is showNumbers

      You could call this function in the context of an arbitrary object, adding this function as a property of an object, and then calling it in the context of this object would mean this object.

      • "If the function is called in the global scope," - it seems to me, it should be removed or changed to "without specifying the context." - Igor
      • @Igor The very first phrase gives an explanation. - Vlad from Moscow
      • I meant that the emphasis should not be on "where", but on "how." - Igor
      • @Igor Here, the one and the other takes place, since the function could be defined inside another function that is called in the context of some object. - Vlad from Moscow
      • @Igor, either it’s a switch function or a wrapped object returned by bind - Grundy