给个例子看看
function Person1(name){
this.name = name;
}
function Person2(name){
this.name = name;
return this.name;
}
function Person3(name){
this.name = name;
return new String(name);
}
function Person4 (name){
this.name = name;
return function () {
}
}
function Person5(name){
this.name = name;
return new Array();
}
const person1 = new Person1("yuer");//Person1 {name: "yuer"}
const person2 = new Person2("yuer");//Person2 {name: "yuer"}
const person3 = new Person3("yuer");//String {0: "y", 1: "u", 2: "e", 3: "r", length: 4, [[PrimitiveValue]]: "yuer"}
const person4 = new Person4("yuer");//function() {}
const person5 = new Person5("yuer");//[]
这里给出了5个例子,其实new操作符干了以下三步:
1.先创建了一个新的空对象
2.然后让这个空对象的__proto__
指向函数的原型prototype
3.将对象作为函数的this传进去,如果return 出来东西是对象的话就直接返回 return 的内容,没有的话就返回创建的这个对象
对应伪代码:
对于const a = new Foo();,new干了以下事情
const o = new Object();//创建了一个新的空对象o
o.__proto__ = Foo.prototype;//让这个o对象的` __proto__`指向函数的原型`prototype`
Foo.call(o);//this指向o对象
a = o;//将o对象赋给a对象
每天都努力一点点
谢谢你看完