1、在构造函数内部隐式创造了一个this空对象,然后把赋值的属性都添加到this对象里面,也就是实参赋值形参,形参赋值给对象键值对的过程
2、隐式return this对象,也就是new Car()赋值给全局变量car,这个时候this的默认指向window转变指向了car,也从全局变量成为了实例对象car
这个时候的car对象,保存了this对象里面的全部键值对
function Car(color,brand){
//this = {};
this.color = color;
this.brand = brand;
// return this;
}
var car = new Car(‘red‘,‘ford‘)
console.log(car.brand);
输出:ford
既然知道了new在这个过程中都做了什么,那么不用new关键字是否可以实现上述过程呢?
1、自己显式构造一个空对象me
2、向空对象里面添加键值对
3、显式的返回me
function Car(color,brand){
var me = {};
me.color = color;
me.brand = brand;
return me;
}
var car = Car(‘red‘,‘ford‘)
console.log(car.brand);
输出:ford
原文:https://www.cnblogs.com/razzh/p/14727110.html