- 正常的
function Car(color) {
// var this = {}; // this = Object.creat(Car.prototype);
this.name = 'BMW';
this.color = color;
// return this
}
var car1 = new Car('red');
// 当函数执行前加 new 关键字,则在函数隐式执行两个步骤。
// 此隐式 this 不可写成显示,不然报错:
// test.html:13 Uncaught SyntaxError: Unexpected token 'this'
- 模拟构造函数隐式步骤
function Car(color) {
var that = {};
that.name = 'BMW';
that.color = color;
return that
}
var car1 = Car('red'); // 不写 new
- 正常的构造函数里不可写return 引用值,不然new了后的返回值不正常。
function Car(color) {
this.name = 'BMW';
this.color = color;
return {};
}
var car1 = new Car('red'); // car1 = {}, 而不是 {name: ...}
// new 出来的返回值不可能是原始值。