Javascript模擬實現new原理解析
new是JS中的一個關鍵字,用來將構造函數實例化的一個運算符。例子:
function Animal(name) { this.name = name;}Animal.prototype.sayName = function() { console.log('I’m ' + this.name);}var cat = new Animal(’Tom’);console.log(cat.name); // Tomconsole.log(cat.__proto__ === Animal.prototype); // truecat.sayName(); // I’m Tom
從上面的例子可以得出兩點結論:
new操作符實例化了一個對象; 這個對象可以訪問構造函數的屬性; 這個對象可以訪問構造函數原型上的屬性; 對象的**__proto__**屬性指向了構造函數的原型;由于new是關鍵字,我們只能去聲明一個函數去實現new的功能,首先實現上面的三個特性,第一版代碼如下:
附:對原型原型鏈不熟悉的可以先看理解Javascript的原型和原型鏈。
// construct: 構造函數function newFunction() { var res = {}; // 排除第一個構造函數參數 var construct = Array.prototype.shift.call(arguments); res.__proto__ = construct.prototype; // 使用apply執行構造函數,將構造函數的屬性掛載在res上面 construct.apply(res, arguments); return res;}
我們測試下:
function newFunction() { var res = {}; var construct = Array.prototype.shift.call(arguments); res.__proto__ = construct.prototype; construct.apply(res, arguments); return res;}function Animal(name) { this.name = name;}Animal.prototype.sayName = function() { console.log('I’m ' + this.name);}var cat = newFunction(Animal, ’Tom’);console.log(cat.name); // Tomconsole.log(cat.__proto__ === Animal.prototype); // truecat.sayName(); // I’m Tom
一切正常。new的特性實現已經80%,但new還有一個特性:
function Animal(name) { this.name = name; return { prop: ’test’ };}var cat = new Animal(’Tom’);console.log(cat.prop); // testconsole.log(cat.name); // undefinedconsole.log(cat.__proto__ === Object.prototype); // trueconsole.log(cat.__proto__ === Animal.prototype); // false
如上,如果構造函數return了一個對象,那么new操作后返回的是構造函數return的對象。讓我們來實現下這個特性,最終版代碼如下:
// construct: 構造函數function newFunction() { var res = {}; // 排除第一個構造函數參數 var construct = Array.prototype.shift.call(arguments); res.__proto__ = construct.prototype; // 使用apply執行構造函數,將構造函數的屬性掛載在res上面 var conRes = construct.apply(res, arguments); // 判斷返回類型 return conRes instanceof Object ? conRes : res;}
測試下:
function Animal(name) { this.name = name; return { prop: ’test’ };}var cat = newFunction(Animal, ’Tom’);console.log(cat.prop); // testconsole.log(cat.name); // undefinedconsole.log(cat.__proto__ === Object.prototype); // trueconsole.log(cat.__proto__ === Animal.prototype); // false
以上代碼就是我們最終對new操作符的模擬實現。我們再來看下官方對new的解釋
引用MDN對new運算符的定義:
new 運算符創建一個用戶定義的對象類型的實例或具有構造函數的內置對象的實例。
new操作符會干下面這些事:
創建一個空的簡單JavaScript對象(即{}); 鏈接該對象(即設置該對象的構造函數)到另一個對象 ; 將步驟1新創建的對象作為this的上下文 ; 如果該函數沒有返回對象,則返回this。4條都已經實現。還有一個更好的實現,就是通過Object.create去創建一個空的對象:
// construct: 構造函數function newFunction() { // 通過Object.create創建一個空對象; var res = Object.create(null); // 排除第一個構造函數參數 var construct = Array.prototype.shift.call(arguments); res.__proto__ = construct.prototype; // 使用apply執行構造函數,將構造函數的屬性掛載在res上面 var conRes = construct.apply(res, arguments); // 判斷返回類型 return conRes instanceof Object ? conRes : res;}
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持好吧啦網。
相關文章:
