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.
It is NOT 'bad' to use the new keyword. But if you forget it, you will be calling the object constructor as a regular function. If your constructor doesn't check its execution context then it won't notice that 'this' points to different object (ordinarily the global object) instead of the new instance.
New keyword in JavaScript is used to create an instance of an object that has a constructor function. On calling the constructor function with 'new' operator, the following actions are taken: A new empty object is created.
The new keyword is used in javascript to create a object from a constructor function. The new keyword has to be placed before the constructor function call and will do the following things: Creates a new object. Sets the prototype of this object to the constructor function's prototype property.
The new keyword in JavaScript: The new keyword is used to create an instance of a user-defined object type and a constructor function. It is used to constructs and returns an object of the constructor function.
When a function is invoked like this
klass(6); //called function invocation
this
will be set to the global object, or, if you're in strict mode, undefined
As a result, the first example (without the new
) will return the global object with a new a
property attached. In strict mode it will throw an error since this
will be set to undefined
, and you can't add an a
property to undefined
.
When you invoke a function with new
new klass( 9 ); //called constructor invocation
the this
value is set to a new object, and is implicitly returned from the function—there's no need to say return this
For completeness, when you invoke a function as a method on an object:
foo.method(); //called method invocation
this
will be set to the object—foo
in this case.
And when you invoke a function with apply (or call)
method.apply(foo) //called apply invocation
this
is 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 of it.
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