前言
現(xiàn)在的前端門(mén)檻越來(lái)越高,不再是只會(huì)寫(xiě)寫(xiě)頁(yè)面那么簡(jiǎn)單。模塊化、自動(dòng)化、跨端開(kāi)發(fā)等逐漸成為要求,但是這些都需要建立在我們牢固的基礎(chǔ)之上。不管框架和模式怎么變,把基礎(chǔ)原理打牢才能快速適應(yīng)市場(chǎng)的變化。下面介紹一些常用的源碼實(shí)現(xiàn):
* call實(shí)現(xiàn)
* bind實(shí)現(xiàn)
* new實(shí)現(xiàn)
* instanceof實(shí)現(xiàn)
* Object.create實(shí)現(xiàn)
* 深拷貝實(shí)現(xiàn)
* 發(fā)布訂閱模式
call
call用于改變函數(shù)this指向,并執(zhí)行函數(shù)
一般情況,誰(shuí)調(diào)用函數(shù),函數(shù)的this就指向誰(shuí)。利用這一特點(diǎn),將函數(shù)作為對(duì)象的屬性,由對(duì)象進(jìn)行調(diào)用,即可改變函數(shù)this指向,這種被稱(chēng)為隱式綁定。apply
實(shí)現(xiàn)同理,只需改變?nèi)雲(yún)⑿问健?br>let obj = { name: 'JoJo' } function foo(){ console.log(this.name) } obj.fn =
foo obj.fn() // log: JOJO
實(shí)現(xiàn)
Function.prototype.mycall = function () { if(typeof this !== 'function'){
throw 'caller must be a function' } let othis = arguments[0] || window
othis._fn = this let arg = [...arguments].slice(1) let res = othis._fn(...arg)
Reflect.deleteProperty(othis, '_fn') //刪除_fn屬性 return res }
使用
let obj = { name: 'JoJo' } function foo(){ console.log(this.name) }
foo.mycall(obj) // JoJo
bind
bind用于改變函數(shù)this指向,并返回一個(gè)函數(shù)
注意點(diǎn):
* 作為構(gòu)造函數(shù)調(diào)用的this指向
* 維護(hù)原型鏈 Function.prototype.mybind = function (oThis) { if(typeof this !=
'function'){ throw 'caller must be a function' } let fThis = this
//Array.prototype.slice.call 將類(lèi)數(shù)組轉(zhuǎn)為數(shù)組 let arg =
Array.prototype.slice.call(arguments,1) let NOP = function(){} let fBound =
function(){ let arg_ = Array.prototype.slice.call(arguments) // new 綁定等級(jí)高于顯式綁定
// 作為構(gòu)造函數(shù)調(diào)用時(shí),保留指向不做修改 // 使用 instanceof 判斷是否為構(gòu)造函數(shù)調(diào)用 return fThis.apply(this
instanceof fBound ? this : oThis, arg.concat(arg_)) } // 維護(hù)原型
if(this.prototype){ NOP.prototype = this.prototype } fBound.prototype = new
NOP() return fBound }
使用
let obj = { msg: 'JoJo' } function foo(msg){ console.log(msg + '' + this.msg)
} let f = foo.mybind(obj) f('hello') // hello JoJo
new
new使用構(gòu)造函數(shù)創(chuàng)建實(shí)例對(duì)象,為實(shí)例對(duì)象添加this屬性和方法
new的過(guò)程:
* 創(chuàng)建新對(duì)象
* 新對(duì)象__proto__指向構(gòu)造函數(shù)原型
* 新對(duì)象添加屬性方法(this指向)
* 返回this指向的新對(duì)象 function new_(){ let fn =
Array.prototype.shift.call(arguments) if(typeof fn != 'function'){ throw fn + '
is not a constructor' } let obj = {} obj.__proto__ = fn.prototype let res =
fn.apply(obj, arguments) return typeof res === 'object' ? res : obj }
instanceof
instanceof 判斷左邊的原型是否存在于右邊的原型鏈中。
實(shí)現(xiàn)思路:逐層往上查找原型,如果最終的原型為null時(shí),證明不存在原型鏈中,否則存在。
function instanceof_(left, right){ left = left.__proto__ while(left !==
right.prototype){ left = left.__proto__ // 查找原型,再次while判斷 if(left === null){
return false } } return true }
Object.create
Object.create創(chuàng)建一個(gè)新對(duì)象,使用現(xiàn)有的對(duì)象來(lái)提供新創(chuàng)建的對(duì)象的__proto__,第二個(gè)可選參數(shù)為屬性描述對(duì)象
function objectCreate_(proto, propertiesObject = {}){ if(typeof proto !==
'object' || typeof proto !== 'function' || proto !== null){ throw('Object
prototype may only be an Object or null:'+proto) } let res = {} res.__proto__ =
proto Object.defineProperties(res, propertiesObject) return res }
深拷貝
深拷貝為對(duì)象創(chuàng)建一個(gè)相同的副本,兩者的引用地址不相同。當(dāng)你希望使用一個(gè)對(duì)象,但又不想修改原對(duì)象時(shí),深拷貝是一個(gè)很好的選擇。這里實(shí)現(xiàn)一個(gè)基礎(chǔ)版本,只對(duì)對(duì)象和數(shù)組做深拷貝。
實(shí)現(xiàn)思路:遍歷對(duì)象,引用類(lèi)型使用遞歸繼續(xù)拷貝,基本類(lèi)型直接賦值
function deepClone(origin) { let toStr = Object.prototype.toString let
isInvalid = toStr.call(origin) !== '[object Object]' && toStr.call(origin) !==
'[object Array]' if (isInvalid) { return origin } let target =
toStr.call(origin) === '[object Object]' ? {} : [] for (const key in origin) {
if (origin.hasOwnProperty(key)) { const item = origin[key]; if (typeof item ===
'object' && item !== null) { target[key] = deepClone(item) } else { target[key]
= item } } } return target }
發(fā)布訂閱模式
發(fā)布訂閱模式在實(shí)際開(kāi)發(fā)中可以實(shí)現(xiàn)模塊間的完全解耦,模塊只需要關(guān)注事件的注冊(cè)和觸發(fā)。
發(fā)布訂閱模式實(shí)現(xiàn)EventBus:
class EventBus{ constructor(){ this.task = {} } on(name, cb){
if(!this.task[name]){ this.task[name] = [] } typeof cb === 'function' &&
this.task[name].push(cb) } emit(name, ...arg){ let taskQueen = this.task[name]
if(taskQueen && taskQueen.length > 0){ taskQueen.forEach(cb=>{ cb(...arg) }) }
} off(name, cb){ let taskQueen = this.task[name] if(taskQueen &&
taskQueen.length > 0){ let index = taskQueen.indexOf(cb) index != -1 &&
taskQueen.splice(index, 1) } } once(name, cb){ function callback(...arg){
this.off(name, cb) cb(...arg) } typeof cb === 'function' && this.on(name,
callback) } }
使用
let bus = new EventBus() bus.on('add', function(a,b){ console.log(a+b) })
bus.emit('add', 10, 20) //30
熱門(mén)工具 換一換
