1. 程式人生 > >前端的幾種手寫程式碼實現

前端的幾種手寫程式碼實現

前言

現在的前端門檻越來越高,不再是隻會寫寫頁面那麼簡單。模組化、自動化、跨端開發等逐漸成為要求,但是這些都需要建立在我們牢固的基礎之上。不管框架和模式怎麼變,把基礎原理打牢才能快速適應市場的變化。下面介紹一些常用的原始碼實現:

  • call實現
  • bind實現
  • new實現
  • instanceof實現
  • Object.create實現
  • 深拷貝實現
  • 釋出訂閱模式

call

call用於改變函式this指向,並執行函式

一般情況,誰呼叫函式,函式的this就指向誰。利用這一特點,將函式作為物件的屬性,由物件進行呼叫,即可改變函式this指向,這種被稱為隱式繫結。apply實現同理,只需改變入參形式。

let obj = {
  name: 'JoJo'
}
function foo(){
  console.log(this.name)
}
obj.fn = foo
obj.fn() // log: JOJO

實現

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用於改變函式this指向,並返回一個函式

注意點:

  • 作為建構函式呼叫的this指向
  • 維護原型鏈
Function.prototype.mybind = function (oThis) {
  if(typeof this != 'function'){
    throw 'caller must be a function'
  }
  let fThis = this
  //Array.prototype.slice.call 將類陣列轉為陣列
  let arg = Array.prototype.slice.call(arguments,1)
  let NOP = function(){}
  let fBound = function(){
    let arg_ = Array.prototype.slice.call(arguments)
    // new 繫結等級高於顯式繫結
    // 作為建構函式呼叫時,保留指向不做修改
    // 使用 instanceof 判斷是否為建構函式呼叫
    return fThis.apply(this instanceof fBound ? this : oThis, arg.concat(arg_))
  }
  // 維護原型
  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使用建構函式建立例項物件,為例項物件新增this屬性和方法

new的過程:

  1. 建立新物件
  2. 新物件__proto__指向建構函式原型
  3. 新物件新增屬性方法(this指向)
  4. 返回this指向的新物件
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 判斷左邊的原型是否存在於右邊的原型鏈中。

實現思路:逐層往上查詢原型,如果最終的原型為null時,證明不存在原型鏈中,否則存在。

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建立一個新物件,使用現有的物件來提供新建立的物件的__proto__,第二個可選引數為屬性描述物件

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
}

深拷貝

深拷貝為物件建立一個相同的副本,兩者的引用地址不相同。當你希望使用一個物件,但又不想修改原物件時,深拷貝是一個很好的選擇。這裡實現一個基礎版本,只對物件和陣列做深拷貝。

實現思路:遍歷物件,引用型別使用遞迴繼續拷貝,基本型別直接賦值

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
}

釋出訂閱模式

釋出訂閱模式在實際開發中可以實現模組間的完全解耦,模組只需要關注事件的註冊和觸發。

釋出訂閱模式實現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