I am very confused about how constructors work in JavaScript; despite using the language for several years (mostly as if it were like a semi-imperative version of Lisp) I would like to know more about how objects are supposed to work in it.
Given this code:
function Foo(x) {
return {
bar: function() { return x; }
};
}
What is the difference between calling myFoo = Foo(5) and myFoo = new Foo(5)? Or, in other words, what exactly does a constructor in JavaScript do?
There’s no difference for that code, because it returns an object, and the spec says:
Since that function returns a result that is an Object, its result is used. You would notice a difference if it did not return an object, or if it checked
this, for example if you rewrote it as:The
newoperator causes the function to be called withthisbound to a newly createdObjectwhose prototype is that function’sprototypeproperty.For user-defined functions,
is equivalent to
Note, that the language specification actually defines functions with two operations, [[Call]] and [[Construct]], so there are some corner cases where
newbehaves oddly.For example, bound and built-in functions:
should define a function that when called, just calls
f, sogshould be the same asfin all respects, butproduces
because the builtin function
Function.prototype.callsupports [[Call]] but not [[Construct]].Function.prototype.bindalso behaves differently aroundnewand regular calls. Thethisvalue is always the bound thisValue when called, but is a newly constructed instance when you usenew.