🐂(new)背后的故事

new Foo() 的背后到底发生了什么

1
2
3
function Foo() {}

var f = new Foo()

🐂 背后的故事到底是什么?

  • 一个新对象 f 生成了,它继承了 Foo 的 prototype
    A new object is created, inheriting from Foo.prototype

  • 构造函数 Foo 被执行了,Foo 中的 this 绑定给了新生成的对象 f
    The constructor function Foo is called with the specified arguments, and with this bound to the newly created object. new Foo is equivalent to new Foo(), i.e. if no argument list is specified, Foo is called without arguments.

  • 如果没有在 Foo 中显示的 return 一个对象, 那么 f 就等于默认构造出来的对象
    The object returned by the constructor function becomes the result of the whole new expression. If the constructor function doesn’t explicitly return an object, the object created in step 1 is used instead. (Normally constructors don’t return a value, but they can choose to do so if they want to override the normal object creation process.)

1
2
3
4
5
6
7
function Car() {}

var c = new Car()

Car.prototype.name = 'bmw'

console.log(c.name)

根据上面的结论,当 c 对象生成时,它继承了 Car.protptype,所以当

1
Car.prototype.name = 'bmw'

执行后,c 对象也有 name 属性,即来自 Car.prototype 的属性

一个思考?下面的代码会打印出什么?

1
2
3
4
5
6
7
function Foo(name) {
this.name = name
return null
}

var f = new Foo('xwill')
console.log(f)

结果:

1
{ name: 'xwill' }

new operator