There is a pattern that prevents problems that can arise if you call a constructor in JavaScript without the keyword new :

function Waffle() { if (!(this instanceof Waffle)) { return new Waffle(); } this.tastes = "yummy"; // Почему это свойство запишется в объект? // Ведь мы же уже возвратили объект из конструктора } Waffle.prototype.wantAnother = true; var test = Waffle(); console.log(test.wantAnother); console.log(test.tastes); 

I do not understand why the tastes property is written to instances of the Waffle class. After all, before assigning it, we returned an object from the constructor (when the constructor was called without new )
Note. The example is taken from the book "Stoyan Stefanov. Javascript. Templates"

    2 answers 2

    The algorithm is as follows:

    1. var test = Waffle(); (a call without new will return us a new Waffle, that is, the constructor function will be called, the condition will work);
    2. since the function was called (it called itself in the condition) already with the new keyword, the condition will not work and this.tastes will be written to our instance

    That is, the first time the condition worked and the function was called, and then the property was recorded. This is the essence of this example.

      When calling a function without the new keyword, the value of this may vary.

      In this case, if this not a created object, the constructor is started manually.

       new Waffle(); 

      and the created object is returned, and already in this launch, the tastes field is tastes - since this now points to the created object.