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 );
?
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.
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