For example I have this function that builds a Car object.
function Car() {
var honkCount = 0;
var honkHorn = function () {
honkCount++;
$results.html('HONK!<br />');
};
return {
get honkCount() {
return honkCount;
},
honk: honkHorn
}
}
Both var car = new Car(); and var car = Car(); don't seem to make much difference and I'm confusing myself a bit.
There is no big difference between using the new operator and dropping it when you're returning an object.
Quoting "JavaScript Garden":
If the function that was called has no explicit return statement, then it implicitly returns the value of this - the new object. In case of an explicit return statement, the function returns the value specified by that statement, but only if the return value is an Object.
The language specification tells us this:
If Type(result) is Object then return result.
Return obj.
In the [[construct]] algorithm that specifies how constructors are done.
However, for you ambitious types - Let's explore why in the language specification together! How could we have figured it out on our own?
Here is why, we're evaluating new NewExpression where newExpression is your function. I got there by checking what the new keyword does in the index.
First:
- Let ref be the result of evaluating NewExpression.
This is the function call
Then:
- Let constructor be GetValue(ref).
Which inside GetValue goes to:
Return the result of calling the GetBindingValue (see 10.2.1) concrete method of base passing GetReferencedName(V) and IsStrictReference(V) as arguments.
This returns the function itself (based on this)
If Type(constructor) is not Object, throw a TypeError exception.
Functions are objects in JS, so it's all good.
If constructor does not implement the [[Construct]] internal method, throw a TypeError exception.
This checks if it's a function. All function have a construct method (looking at a function as a constructor, you can try evaluating (function(){}).constructor and see.
Return the result of calling the [[Construct]] internal method on constructor, providing no arguments (that is, an empty list of arguments).
Great! Let's see what [[construct]] does. It's defined in 13.3.2, and it says a bunch of things. The Jackpot is this:
Let result be the result of calling the [[Call]] internal property of F, providing obj as the this value and providing the argument list passed into [[Construct]] as args.
If Type(result) is Object then return result. Return obj.
So internally, the spec says that if your function returns an object, the constructor returns it instead of the object created.
Note (One very minor difference is that when you're not in strict mode, using new might catch a bug )
Bonus: Here is a nice explanation on constructors from JavaScript garden
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With