Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

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

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

is

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

any different than

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

?

like image 823
Sled Avatar asked Jan 29 '13 15:01

Sled


1 Answers

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

The equivalent version would be

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

Is it syntactic sugar? Might depend on how you define it.

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


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

like image 106
Felix Kling Avatar answered Sep 22 '22 19:09

Felix Kling