new Foo(...)
调用时会执行以下步骤:
- 创建一个空的JavaScript对象,并继承
Foo.prototype
var obj
obj.prototype = Object.create(Foo.prototype)
- 使用指定的参数调用构造函数Foo,并将
this
绑定到新创建的对象。new Foo等价于new Foo(),即如果没有指定参数列表,则调用Foo时没有参数。
Foo.call(obj, ...)
- 构造函数返回的对象(不是null、false、3.1415或其他基本类型)成为整个新表达式的结果。如果构造函数没有显式返回对象,则使用步骤1中创建的对象。(通常构造函数不返回值,但如果它们想覆盖正常的对象创建过程,则可以选择这样做。)
// 如果Foo没有显式返回对象
return obj
一言以蔽之,new一个对象就是创建一个新对象,这个新对象既拥有Foo
的constructor里的属性,又继承了Foo.prototype
,并返回这个新对象。
示例:
function Person(name) {
this.name = name
}
var a = new Person('Johnson')
console.log(Person.prototype.isPrototypeOf(a)) // true
console.log(a.constructor === Person) //true
console.log(a instanceof Person) // true
console.log(a.name) //Johnson
console.log(Object.prototype.toString.call(a)) // "[object Object]"