When a function like this is called
klass(6); //called function invocation
this will set the global object or, if you are in strict mode, undefined
As a result, the first example (without new ) will return a global object with a new property a attached. In strict mode, it throws an error, since this will be set to undefined , and you cannot add the a property to undefined .
When calling a function with new
new klass( 9 );
this value is set to a new object and implicitly returned from the function - no need to say return this
For completeness, when you call a function as a method for an object:
foo.method();
this will be set in the foo object in this case.
And when you call the function using (or calling)
method.apply(foo)
this set to whatever you specify - foo again
EDIT
I mentioned strict mode in my answer. A page uses strict mode if it has
"use strict"
at the very top.
source share