詳解JavaScript中new操作符的解析和實現(xiàn)
前言
new 運算符是我們在用構(gòu)造函數(shù)創(chuàng)建實例的時候使用的,本文來說一下 new 運算符的執(zhí)行過程和如何自己實現(xiàn)一個類似 new 運算符的函數(shù)。
new 運算符的運行過程
new 運算符的主要目的就是為我們創(chuàng)建一個用戶定義的對象類型的實例或具有構(gòu)造函數(shù)的內(nèi)置對象的實例(比如箭頭函數(shù)就沒有構(gòu)造函數(shù),所以是不能 new 的)。new 操作符的執(zhí)行大概有以下幾個步驟:
創(chuàng)建一個新的空對象 把新對象的 __proto__ 鏈接到構(gòu)造函數(shù)的 prototype 對象(每一個用戶定義函數(shù)都有一個 prototype 屬性指向一個對象,該對象有一個 constructor 屬性指向該函數(shù)),讓我們的公共屬性和方法可以從原型上繼承,不用每個實例都創(chuàng)建一次。 將第一步創(chuàng)建的新的對象作為構(gòu)造函數(shù)的 this 的上下文,執(zhí)行構(gòu)造函數(shù),構(gòu)造函數(shù)的執(zhí)行讓我們配置對象的私有屬性和方法。 執(zhí)行構(gòu)造函數(shù),如果構(gòu)造函數(shù)沒有返回值或者返回值不是一個對象,則返回 this。我么可以用代碼簡單表示上面的邏輯:
function new_ (constr, ...rests) { var obj = {}; obj.__proto__ = constr.prototype; var ret = constr.apply(obj, rests); return isPrimitive(ret) ? obj : ret; //判斷構(gòu)造函數(shù)的返回值是否為對象,不是則直接返回創(chuàng)建的obj對象}
new 的實現(xiàn)
上面講了 new 運算符的執(zhí)行過程,下面我們來自己動手實現(xiàn)一個 new 運算符。
function new_(constr, ...rests) { if (typeof constr !== 'function') { throw 'the first param must be a function'; } new_.target = constr; var obj = Object.create(constr.prototype); var ret = constr.apply(obj, rests); var isObj = typeof ret !== null && typeof ret === 'object'; var isFun = typeof ret === 'function'; //var isObj = typeof ret === 'function' || typeof ret === 'object' && !!ret; if (isObj || isFun) { return ret; } return obj;}function Person(name, age) { this.name = name; this.age = age;}Person.prototype.say = function () { console.log(this.name);};var p1 = new_(Person, ’clloz’, ’28’)var p2 = new_(Person, ’csx’, ’31’)console.log(p1); //Person {name: 'clloz', age: '28'}p1.say(); //cllozconsole.log(p2); //Person {name: 'csx', age: '31'}p2.say(); //csxconsole.log(p1.__proto__ === Person.prototype); //trueconsole.log(p2.__proto__ === Person.prototype); //true
以上就是一個簡單的 new 實現(xiàn),判斷是否為對象那里可能不是很嚴謹,不過沒有想到更好的方法。
一個小補充,在 mdn 的 Function.prototype.apply() 詞條中看到的直接把方法寫到 Function.prototype 上,也是個不錯的思路,F(xiàn)unction.prototype 在所以函數(shù)的原型鏈上,所以這個方法可以在每個函數(shù)上調(diào)用,方法內(nèi)部的 this 也是指向調(diào)用方法的函數(shù)的。
Function.prototype.construct = function (aArgs) { var oNew = Object.create(this.prototype); this.apply(oNew, aArgs); return oNew;};
強制用 new 調(diào)用構(gòu)造函數(shù)
function Clloz(...arguments) { if (!(this instanceof Clloz)) { return new Clloz(...arguments) }}
Tips
補充兩個關(guān)于 new 運算符的知識點。
上面提到 new 的執(zhí)行過程的最后一步,如果構(gòu)造函數(shù)沒有返回值或者返回值不是一個對象,則返回 this。但是如果返回的是一個 null 的話,依然返回 this,雖然 null 也算是 object。 new 操作符后面的構(gòu)造函數(shù)可以帶括號也可以不帶括號,除了帶括號可以傳遞參數(shù)以外,還有一個重要的點是兩種用法的運算符優(yōu)先級不一樣,在JS運算符優(yōu)先級這篇文章中有提到,帶參數(shù)的 new 操作符的優(yōu)先級是比不帶參數(shù)的要高的,new Foo() > Foo() > new Foo。一般不太會遇到,可能有些題目會問這些問題。
以上就是詳解JavaScript中new操作符的解析和實現(xiàn)的詳細內(nèi)容,更多關(guān)于JavaScript new解析和實現(xiàn)的資料請關(guān)注好吧啦網(wǎng)其它相關(guān)文章!
相關(guān)文章:
