Is `new` in JavaScript just syntactic sugar for `.call`?

In JavaScript, I was wondering if there is anything special in new or is it just syntactic sugar for call() . If I have a constructor like:

 function Person ( name, age ){ this.name = name; this.age = age; } 

there is

 var bob = new Person( "Bob", 55 ); 

different

 var bob; Person.call( bob = new Object(), "Bob", 55 ); 

?

+7
source share
6 answers

They are not equivalent in your example, because bob does not inherit from Person.prototype (it directly inherits from Object.prototype ).

Equivalent version will be

 Person.call(bob = Object.create(Person.prototype), "Bob", 55 ); 

Is it syntactic sugar? Perhaps it depends on how you define it.

Object.create not available in earlier versions of JS, so it was not possible to set up object inheritance without new (you can overwrite the internal property __proto__ object in some browsers, but this is really bad practice).


As a reference, how new works at http://es5.github.com/#x11.2.2 and http://es5.github.com/#x13.2.2 . Object.create described at http://es5.github.com/#x15.2.3.5 .

+3
source

No, new is not just syntactic sugar. On the contrary, Person.call works (and only works) to build a new instance, because JavaScript allows you to call constructors without new at any time.

+2
source

Not

call() simply calls the function (see also apply() ), while the new keyword initializes the object from the prototype.

Although it is true that the prototype constructor is a function, this is a special case.

+2
source

No no. If your first example, you are actually creating a Person.

 bob instanceof Person == true 

In another example ...

 bob instanceof Person == false 
+2
source

The point of creating an instance of a type is to share some behavior, usually with a prototype.

Say you added a function:

 Person.prototype.doSomething = function(){ ... } 

This function will then be available to all objects created as instances of Person using new , but not to an object created using call .

MDN has a good introductory document about using a prototype .

+1
source

When you call new , you call the function as a constructor. This tells JavaScript to create a β€œnew” Person object and then call a function with this new object set to this .

In your second example, you usually call a function and manually set this to a new Object (or just {} ). Thus, the function is launched and sets the properties of the this object that you sent. (Try just doing Person( "Bob", 55 ); then console.log(window.name) )

In the first example, bob is a Person object; but in the 2nd, it is Object .

So no, one is not short for the other. They are different.

+1
source

All Articles