創(chuàng)建一個(gè)新的空對(duì)象
將構(gòu)造函數(shù)的作用域賦給新對(duì)象(this指向它)
新對(duì)象增加構(gòu)造函數(shù)的基本方法和屬性。
返回新對(duì)象
實(shí)現(xiàn)
function create() {
//創(chuàng)建一個(gè)空對(duì)象
let obj = new Object();
//獲取構(gòu)造函數(shù)
let Constructor = [].shift.call(arguments);
//鏈接到原型
obj._proto_ = Constructor.prototype;
//綁定this值
let result = Constructor.apply(obj, arguments); //使用apply,將構(gòu)造函數(shù)中的this指向新對(duì)象,這樣新對(duì)象就可以訪問構(gòu)造函數(shù)中的屬性和方法
//返回新對(duì)象
return typeof result === "object" ? result : obj; //如果返回值是一個(gè)對(duì)象就返回該對(duì)象,否則返回構(gòu)造函數(shù)到一個(gè)實(shí)例對(duì)象
}
使用
function People(name, age) {
this.name = name;
this.age = age;
}
//通過new創(chuàng)建構(gòu)造實(shí)例
let people1 = new People("Jack", 20);
console.log(people1.name); //Jack
console.log(people1.age); //20
//通過create方法創(chuàng)建實(shí)例
let people2 = create(People, "Rose", 18);
console.log(people2.name); //Rose
console.log(people2.age); //18