Back
The new keyword in JavaScript can be quite confusing when it is first encountered, as people tend to think that JavaScript is not an object-oriented programming language.
What is it?
What problems does it solve?
When is it appropriate and when not?
The new keyword in JavaScript creates a new object. The type of this object simply objects.
Also, it makes this variable point to the newly created object.
New keyword executes the constructor function, using the newly created object whenever this is mentioned.
See the code below to understand new keywords practical uses:-
function Foo() { return this; } var a = Foo(); var b = new Foo();a instanceof Window; a instanceof Foo; instanceof Window; b instanceof Foo;
function Foo() {
return this;
}
var a = Foo();
var b = new Foo();
a instanceof Window;
a instanceof Foo;
instanceof Window;
b instanceof Foo;
31k questions
32.8k answers
501 comments
693 users