使用js實現一個new方法
阿新 • • 發佈:2020-12-19
技術標籤:javascriptjs
js實現一個new
在開發過程中,我們經常會使用new關鍵字,那我們在使用new關鍵字的時候,new到底做了什麼呢?我們可以查閱資料,在MDN中有這樣一段話
new 運算子建立一個使用者定義的物件型別的例項或具有建構函式的內建物件的例項。new 關鍵字會進行如下的操作: 1. 建立一個空的javascript物件就比如(即{}); 2. 連結該物件(即設定該物件的建構函式)到另一個物件; 3. 將步驟1新建立的物件作為this的上下文; 4. 如果該函式有沒有返回物件,沒有則返回this; 知道了new的這些功能,我們就能根據這些步驟來實現一個new的功能了!
程式碼示例
function _new(constructer, ...arg) {
// 建立一個空的物件
let resultObj = {};
// 連結該物件到原型,這樣新物件就能訪問到原型上面的方法
resultObj.__proto__ = constructer.prototype;
// 然後實現步驟3,將新建立的物件作為this的上下文
let result = constructer.call(resultObj, ...arg);
// 實現步驟4:如果該函式沒有返回物件(即result不是一個物件),則返回this(即resultObj)
return typeOf result === 'object' ? result : resultobj
// 接下來就可以看看new的實現效果了
}
new方法的效果:
function Persion(name, age) {
this.name = name;
this.age = age;
}
let Persion1 = _new(Persion, 'lucy', '18');
let Persion2 = _new(Persion, 'chuan', '20');
console.log(Persion1.name); // 'lucy'
console.log( Persion1.name); // 'chuan'
console.log(Persion1 instanceof Persion); // true
console.log(Persion2 instanceof Persion); // true