Consider the following code:
var f = function() { return 10; }
typeof f; // returns "function"
f(); // returns 10
var g = f;
g(); // returns 10, obviously
var h = new f;
h; // console evaluates to f - ????
h(); // Type error - called_non_callable
typeof h; // returns "object"
So, what is h here? The Chrome console seems to evaluate it as f, but it isn’t callable. What does it mean to “new” a function like this? How is h now related to f?
As an aside, these two lines appear to be equivalent:
var h = new f;
var h = new f();
What’s up with that?
The root of your confusion is the way that Chrome represents objects on its console.
The expression
new f()in your example is represented as ‘f‘ on the Chrome’s console output, but just as a mere “convenience” of this particular console, for example, logging the following object:Will show it represented as “
Foo“. Basically the console tries to find a representation of which constructor your object is instance of.So, the console shows you
f, but you are not logging the function, thenewoperator produces an object that inherits fromf.prototype.You are returning
10from the function, but since you call it withnew, and the return type is a primitive, the value is discarded, the newly created object that inherits formf.prototypeis returned.For example:
On the other hand, if you return an object from a constructor, the object instance that the
newoperator creates behind the scened (and inherits from the constructor’s prototype) will be lost, for example:Yes,
new f;andnew f();are completely equivalent, although people recommend using the parentheses to add clarity to your code.