一移袍、在JavaScript
中,new
操作符用于創(chuàng)建一個給定構(gòu)造函數(shù)的實例對象
function Person(name, age){
this.name = name;
this.age = age;
}
Person.prototype.sayName = function () {
console.log(this.name)
}
const person1 = new Person('Tom', 20)
console.log(person1) // Person {name: "Tom", age: 20}
t.sayName() // 'Tom
從上面可以看到:
new 通過構(gòu)造函數(shù) Person 創(chuàng)建出來的實例可以訪問到構(gòu)造函數(shù)中的屬性
new 通過構(gòu)造函數(shù) Person 創(chuàng)建出來的實例可以訪問到構(gòu)造函數(shù)原型鏈中的屬性(即實例與構(gòu)造函數(shù)通過原型鏈連接了起來)
現(xiàn)在在構(gòu)建函數(shù)中顯式加上返回值螟左,并且這個返回值是一個原始類型
function Test(name) {
this.name = name
return 1
}
const t = new Test('xxx')
console.log(t.name) // 'xxx'
可以發(fā)現(xiàn),構(gòu)造函數(shù)中返回一個原始值觅够,然而這個返回值并沒有作用
下面在構(gòu)造函數(shù)中返回一個對象
從上面可以發(fā)現(xiàn),構(gòu)造函數(shù)如果返回值為一個對象喘先,那么這個返回值會被正常使用
流程
從上面介紹中,我們可以看到new關(guān)鍵字主要做了以下的工作:
創(chuàng)建一個新的對象obj
將對象與構(gòu)建函數(shù)通過原型鏈連接起來
將構(gòu)建函數(shù)中的this綁定到新建的對象obj上
根據(jù)構(gòu)建函數(shù)返回類型作判斷窘拯,如果是原始值則被忽略红且,如果是返回對象涤姊,需要正常處理
手寫new操作符
function mynew(Func, ...args) {
// 1.創(chuàng)建一個新對象
const obj = {}
// 2.新對象原型指向構(gòu)造函數(shù)原型對象
obj.proto = Func.prototype
// 3.將構(gòu)建函數(shù)的this指向新對象
let result = Func.apply(obj, args)
// 4.根據(jù)返回值判斷
return result instanceof Object ? result : obj
}