new操作符的实现
new操作符的实现
new操作符主要完成了如下工作:1.创建一个对象,并将它的[[Prototype]]设置为指向构造函数的原型对象。2.将新创建的对象绑定到构造函数的this上,并执行构造函数。3.判断构造函数的返回值是否为一个非空对象,如果是,则返回构造函数的返回值,否则返回之前新创建的对象。
1 const myNew = function (constructorFunction) { 2 if (typeof constructorFunction !== "function") { 3 throw new Error("Contructor must be a function"); 4 } 5 6 // target属性可以用于检测函数或者构造方法是否通过new操作符调用 7 myNew.target = constructorFunction; 8 9 // 将obj的原型设置为构造函数的原型对象 10 let obj = Object.create(constructorFunction.prototype); 11 12 // 获取构造函数的参数 13 let args = [].slice.call(arguments, 1); 14 15 // 执行构造函数 16 let res = constructorFunction.apply(obj, args); 17 18 // 如果构造函数返回非空对象,则返回构造函数的返回值,否则返回新创建的对象 19 if ((typeof res === "object" && res !== null) || typeof res === "function") { 20 return res; 21 } else { 22 return obj; 23 } 24 } 25 26 const Person = function (name, age) { 27 this.name = name; 28 this.age = age; 29 } 30 31 let person = myNew(Person, "Alex", 18); 32 console.log(person.name, person.age); // Alex 18 33 console.log(person.__proto__ === Person.prototype); // true 34 console.log(person.constructor === Person); // true 35 36 let person2 = myNew(Person, "Apple", 20); 37 console.log(person2.prototype === person.prototype); // true

浙公网安备 33010602011771号