new operator关于js的new操作
2016-07-08 本文已影响285人
进击的前端
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的原型。
当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
的结果可以知道了吧?