The behavior of your code is a direct result of the nature of JS Constructors and the new
operator. Also, it is behaving as expected. I assume, however that your question is merely theoretical because I don't really see a valid use case for chaining multiple new
operators.
In your code, foo
is a Constructor, and its only purpose is to specify the type of instance that should be created. In other words, its form/structure.
When you use the new
operator on a Constructor, it creates a plain blank object and links to it the Constructor function (instance.constructor
), then it assigns this newly created object to the this
context of the function and runs it.
If the function returns an object, then new
returns that object too! If not, then new
automatically returns that first created object (this
).
In your case, you are returning a reference to your own Constructor. That is an object. So, new foo;
is always returning a constructor. That is why you are allowed to chain multiple new
operators, which is not possible when using a standard constructor.
To obtain the value of x
, you must return this
inside your constructor or not return an object at all.
Hope this clarifies the inner mechanics of it.
Oh! And despite general knowledge, the use of ()
when using new
operator is not necessary.
Finally, to close the ring, please see the following snipped, using your code:
let x = 0;
function Foo(c){
x++;
this.x = x;
return c ? this : Foo;
}
new new new new new new new new new Foo;
const bar = new Foo(1);
console.log(bar.x); // EXPECTED TO PRINT 10.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…