首頁  >  文章  >  web前端  >  手動實作js中的call、bind、instanceof

手動實作js中的call、bind、instanceof

angryTom
angryTom轉載
2020-02-15 17:55:282569瀏覽

js中call能夠改變this的指向、bind能改變this的指向,並且回傳一個函數,這是怎麼實現的呢?本文將帶你一步一步實現這些功能,希望對學習JavaScript的朋友有幫助。

手動實作js中的call、bind、instanceof

#前言

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

call實作

bind實作

new實作

instanceof實作

##Object .create實作

深拷貝實作

發布訂閱模式

#call

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

(推薦 

js教學 ,歡迎學習!)

一般情況,誰呼叫函數,函數的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的過程:

建立新物件

新物件__proto__指向建構函數原型

新物件新增屬性方法(this指向)

傳回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

以上是手動實作js中的call、bind、instanceof的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:cnblogs.com。如有侵權,請聯絡admin@php.cn刪除