Consider this code:
function klass( z ) {
this.a = z;
return this;
}
var b = klass( 5 );
var c = new klass( 9 );
When I run it in Chrome and check in the console, b turns out to be of type DOMWindow, while c is of type klass.
Although both have the property a, effectively both being an instance of klass.
- Is using or not using new, the same?
- Is it the same on this example but different in other situations?
- Are there differences in efficiency or behavior?
When a function is invoked like this
thiswill be set to the global object, or, if you’re in strict mode,undefinedAs a result, the first example (without the
new) will return the global object with a newaproperty attached. In strict mode it will throw an error sincethiswill be set toundefined, and you can’t add anaproperty toundefined.When you invoke a function with
newthe
thisvalue is set to a new object, and is implicitly returned from the function—there’s no need to sayreturn thisFor completeness, when you invoke a function as a method on an object:
thiswill be set to the object—fooin this case.And when you invoke a function with apply (or call)
thisis set to whatever you specify—fooagainEDIT
I mentioned
strict modein my answer. A page uses strict mode if it hasat the very top of it.