JavaScript中的`new`只是`.call`的语法糖?

Sle*_*led 7 javascript

在JavaScript中,我想知道是否有任何特殊内容new或者它是否仅仅是语法糖call().如果我有一个像这样的构造函数:

function Person ( name, age ){
    this.name = name;
    this.age = age;
}
Run Code Online (Sandbox Code Playgroud)

var bob = new Person( "Bob", 55 );
Run Code Online (Sandbox Code Playgroud)

任何不同的

var bob;
Person.call( bob = new Object(), "Bob", 55 );
Run Code Online (Sandbox Code Playgroud)

Fel*_*ing 4

它们在您的示例中并不等效,因为bob不继承自Person.prototype(它直接继承自Object.prototype)。

等效版本是

Person.call(bob = Object.create(Person.prototype), "Bob", 55 );
Run Code Online (Sandbox Code Playgroud)

它是语法糖吗?可能取决于你如何定义它。

Object.create在早期的 JS 版本中不可用,因此不可能设置对象继承new(您可以在某些浏览器中覆盖对象的内部__proto__属性,但这确实是不好的做法)。


作为参考,http://es5.github.com/#x11.2.2http://es5.github.com/#x13.2.2new中定义了工作原理。在http://es5.github.com/#x15.2.3.5中进行了描述。Object.create