網道 - new 命令的原理
使用new命令時,它后面的函數依次執行下面的步驟。
- 創建一個空對象,作為將要返回的對象實例。
- 將這個空對象的原型,指向構造函數的prototype屬性。
- 將這個空對象賦值給函數內部的this關鍵字。
- 如果構造函數返回了一個對象,則返回該對象,否則返回新創建的對象。
模擬實現
[].slice.call()
將偽數組轉為真數組,等同Array.from()
function _new(constructor, ...args) {// 1. 創建一個空對象,作為將要返回的對象實例。const obj = {}// 2. 將這個空對象的原型,指向構造函數的prototype屬性。obj.__proto__ = constructor.prototype// 3. 將這個空對象賦值給函數內部的this關鍵字。(使用構造函數處理obj作為上下文this)const result = constructor.apply(obj, [].slice.call(args))// 4. 如果構造函數返回了一個對象,則返回該對象,否則返回新創建的對象。return (typeof result === 'object' && result != null) ? result : obj;
}// 使用
function Person(name, age) {this.name = namethis.age = age
}
Person.prototype.say = function() {return `我叫: ${this.name}, 今年: ${this.age} 歲!`
}
const person1 = _new(Person, '張三', 22)
const person2 = _new(Person, '李四', 18)