Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is using new in Javascript the same as not using it?

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?
like image 821
Petruza Avatar asked Dec 23 '11 02:12

Petruza


People also ask

What happens if you don't use new in JavaScript?

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.

What does new mean in JavaScript?

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.

Is new required in JavaScript?

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.

What is the purpose of new keyword?

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.


1 Answers

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.

like image 130
Adam Rackis Avatar answered Oct 10 '22 08:10

Adam Rackis