new,instanceof原理剖析

new 功能分析

看看new 運算符都幹了什麼
1. 創建一個空對象obj
2. 將空對象原型鏈上的__proto__ 指向 構造函數的原型ptototype
3. 綁定this值,將構造函數this指向空對象,並傳入參數
4. 如果構造函數Fn返回值是一個對象或函數,則返回改對象,否則返回obj

 	    function Parent (name,age) {
            this.name = name;
            this.age = age;
        }
        let p1 = new Parent('zs', 33);
        console.log(p1);
      

在這裏插入圖片描述
原理實現

	    function New(fn, ...args) {
            let obj = {};  // 1. 創建空對象
            obj.__proto__ = fn.prototype; // 2.空對象__proto__指構造函數ptototype
            let result = fn.apply(obj, args); // 3. 綁定this指向空對象,傳參
            // 4.如果構造函數fn返回值是對象或函數,使用此返回值
            if (result && (typeof(result) === 'object' || typeof(result) === 'function')) { 
                return result
            }
            return obj   // 否則返回obj
        }

調用函數

 	 let p2 = New(Parent, 'ls', 44)
     console.log(p2);

在這裏插入圖片描述

instanceof 功能分析

1. 滿足 typeof 功能類型的不足,對於複雜數據類型,除了函數都返回object

  typeof([1,2])  // "object"
  typeof({})     // "object"

2. instanceof 內部機制是通過原型鏈來實現的。因此傳入類型需是object類型

1 instanceof Number  // false
new Number(1) instanceof Number  // true

原理實現

 function instance_of (L, R) { // L爲實例(instanceof左邊),R爲構造函數(instanceof右邊)
        let R = R.prototype;  // 構造函數顯式原型
        L = L.__proto__; // 實例隱式原型
        while (true) { 
            if (L === null) return false; 
            if (R == L)  return true;
            L = L.__proto__;  // 獲取父級的__proto__
        }
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章