mdn關于new的英文 當然也有 中文 ,不過總覺得英文好懂一點。
When the code new Foo(...) is executed, the following things happen:
- A new object is created, inheriting from Foo.prototype.
- 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. - 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.)
假如我們new了一個Foo函數,那么發生了什么事情?new操作總共干了三件事。
- 第一件事情就是創造一個繼承 Foo.prototype的新對象。
- 第二件事情就是Foo函數使用new的時候輸入的參數被執行,把Foo函數的this重新綁定新的對象。
- 構造函數Foo執行的返回值作為新的表達式。如果沒有返回,那么之前生成的對象,就作為返回。
所以可能有兩種情況。
第一種當a并沒有返回值的時候,b繼承了a的原型。
a沒有返回值
當c有返回值的時候,d并沒有繼承c的原型
c有返回值
關于this的例子,就是第一種情況,構造函數并沒有返回值。
所以
function Car(make, model, year) {
this.make = make;
this.model = model;
this.year = year;
}
var mycar = new Car("Eagle", "Talon TSi", 1993);
this的結果
所以在前面的基礎上執行下面的代碼
var kenscar = new Car("Nissan", "300ZX", 1992);
function Person(name, age, sex) {
this.name = name;
this.age = age;
this.sex = sex;
}
var rand = new Person("Rand McNally", 33, "M");
var ken = new Person("Ken Jones", 39, "M");
function Car(make, model, year, owner) {
this.make = make;
this.model = model;
this.year = year;
this.owner = owner;
}
var car1 = new Car("Eagle", "Talon TSi", 1993, rand);
var car2 = new Car("Nissan", "300ZX", 1992, ken);
car2.owner.name
的結果可以知道了吧?