JS手寫bind之處理new的情況詳解
大家好,我是前端西瓜哥。
之前寫了一篇關(guān)于 JS 中 bind 方法的實現(xiàn)的文章,并給出了實現(xiàn):
Function.prototype.myBind = function(thisArg, ...prefixArgs) { const fn = this; return function(...args) { return fn.call(thisArg, ...prefixArgs, ...args); } }
但沒有處理 通過 new 創(chuàng)建實例 的情況。
因為很少會遇到給 bind 返回的函數(shù)做 new 操作的場景,所以我沒去考慮這種特殊情況。
但面試中還是會涉及到的,我們還是實現(xiàn)一下兼容 new 操作的 bind 寫法,順便學習一下 new 操作符。
因為存在一定上下文,在閱讀本文前,建議先閱讀前一篇文章:《前端面試題:手寫 bind》。
new
我們先學習一下 new 操作符。
new 用于通過函數(shù)來創(chuàng)建一個對象實例,在很多語言中都能看到。
JS 的函數(shù),除了可以是普通函數(shù),比如:
function sum(a, b) { return a + b; }
還可以是構(gòu)造函數(shù),只需要在構(gòu)造時在它前面加一個 new:
function Person(name, age) { this.name = name; this.age = age; } const person = new Person('前端西瓜哥', 100) // Person {name: '前端西瓜哥', age: 100}
new 創(chuàng)建一個新對象,做了下面幾件事:
- 創(chuàng)建一個空對象
{}
; - 空對象的原型屬性
__proto__
指向構(gòu)造函數(shù)的原型對象Person.prototype
; - 函數(shù)中的 this 設(shè)置為這個空對象;
- 如果該函數(shù)不返回一個對象,就返回這個 this,否則返回這個對象。
判斷函數(shù)是否通過 new 被調(diào)用
怎么判斷一個函數(shù)正在被 new 操作符調(diào)用?
答案是 使用 instanceof 判斷 this 是否為當前函數(shù)的實例,即 this instanceof Fn
為 true,表示在通過 new 構(gòu)建實例。
我們看一個例子:
function Person() { if (this instanceof Person) { console.log('通過 new 構(gòu)建實例'); } else { console.log('普通調(diào)用') } } Person() // 輸出:普通調(diào)用 new Person() // 輸出:通過 new 構(gòu)建實例
在 Vuejs 的源碼,你會看到下面代碼,這里也用到了這個技巧。
function Vue(options) { if (__DEV__ && !(this instanceof Vue)) { warn('Vue is a constructor and should be called with the `new` keyword') } this._init(options) }
你在開發(fā)環(huán)境如果不通過 new 來使用 Vue 對象,會在控制臺提示你要通過 new 來調(diào)用 Vue。
new 和 bind
如果我們 new 的是 Function.prototype.bind 返回的新函數(shù),會發(fā)生什么事情?
function Person(name, age) { this.name = name; this.age = age; } const BoundPerson = Person.bind(null, '前端西瓜哥'); const boundPerson = new BoundPerson(100); // Person {name: '前端西瓜哥', age: 100} boundPerson.__proto__ === Person.prototype // true
結(jié)果等價于直接去 new 原始函數(shù)。
不同的是,仍舊可以進行參數(shù)的預(yù)置??梢钥吹?,構(gòu)造函數(shù)的第一個參數(shù),在調(diào)用 bind 的時候就提前設(shè)置為 '前端西瓜哥'。
實現(xiàn)完整的 bind
完整實現(xiàn)如下:
Function.prototype.myBind = function(thisArg, ...prefixArgs) { const fn = this; const boundFn = function(...args) { // 通過 new 使用當前函數(shù) if (this instanceof boundFn) { return new fn(...prefixArgs, ...args); } // 普通的方法調(diào)用當前函數(shù) return fn.call(thisArg, ...prefixArgs, ...args); } boundFn.prototype = fn.prototype; return boundFn; }
這里我通過 this instanceof boundFn
來判斷是否用了 new,如果是,就直接 new 原始函數(shù)然后返回,記得帶上 bind 預(yù)置好的參數(shù)。
其他保持原樣(具體見上文《前端面試題:手寫 bind》)。
boundFn.prototype = fn.prototype;
這個可寫可不寫,只是讓 bind 返回的新函數(shù)的 prototype 指向原函數(shù)的 prototype。
如果是原生 bind 返回的函數(shù),它是沒有 protoype 屬性的,可以認為它是一種特別的函數(shù),而我們實現(xiàn)的 bind 返回的卻是一個普通函數(shù),所以并不能完全模擬的。
如果你 追求完美的實現(xiàn),可以研讀一下 Function.prototype.bind 的標準:
然后再看看知名的 core.js 庫中對 bind 的實現(xiàn):
其中核心實現(xiàn)為:
// `Function.prototype.bind` method implementation // https://tc39.es/ecma262/#sec-function.prototype.bind module.exports = Function.bind || function bind(that /* , ...args */) { var F = aCallable(this); var Prototype = F.prototype; var partArgs = arraySlice(arguments, 1); var boundFunction = function bound(/* args... */) { var args = concat(partArgs, arraySlice(arguments)); return this instanceof boundFunction ? construct(F, args.length, args) : F.apply(that, args); }; if (isObject(Prototype)) boundFunction.prototype = Prototype; return boundFunction; };
這里有更多的細節(jié):
- 這里判斷了 this 是否為函數(shù)類型,不是函數(shù)會報錯;
- F.prototype 需要是一個對象或函數(shù),才能賦值給新函數(shù);
- 使用了普通函數(shù)和 arguments,這是為了兼容 ES5。
結(jié)尾
手寫 bind,現(xiàn)在想來并不簡單,需要掌握好很多知識點:
- bind 的詳盡用法:包括改變 this、預(yù)置參數(shù)、new 的表現(xiàn);
- 閉包的使用:保存一些私有變量;
- 通過原型鏈的方式(
this instanceof boundFn
)判斷是否通過 new 調(diào)用當前函數(shù); - 使用 call 在執(zhí)行時改變函數(shù)的 this 指向。
到此這篇關(guān)于JS手寫bind之處理new的情況詳解的文章就介紹到這了,更多相關(guān)JS處理new內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
js中document.getElementByid、document.all和document.layers區(qū)分介紹
document.getElementById 是公共標準,被目前的所有主流瀏覽器支持,document.all只有IE支持,document.layers是Netscape 4.x專有的屬性2011-12-12javascript showModalDialog傳值與FireFox的window.open 父子窗口傳值示例
javascript showModalDialog傳值與FireFox的window.open 父子窗口傳值示例代碼。2009-11-11javascript 數(shù)字格式化輸出的實現(xiàn)代碼
這篇文章主要是對javascript中數(shù)字格式化輸出的實現(xiàn)代碼進行了介紹,需要的朋友可以過來參考下,希望對大家有所幫助2013-12-12JavaScript庫urlcat?之URL構(gòu)建器庫
這篇文章主要介紹了JavaScript庫urlcat之URL構(gòu)建器庫,urlcat?是一個小型的JavaScript庫,使構(gòu)建URL非常方便并防止常見錯誤。下文來看對其詳細介紹吧,需要的小伙伴可以參考一下2022-02-02關(guān)于JSON.parse(),JSON.stringify(),jQuery.parseJSON()的用法
下面小編就為大家?guī)硪黄P(guān)于JSON.parse(),JSON.stringify(),jQuery.parseJSON()的用法。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2016-06-06