重寫JS中的apply,call,bind,new方法

在js中,經常會用到applycallbindnew,這幾個方法在前端佔據非常重要的作用,今天來看一下這些方法是如何實現,方便更加深入的理解它們的運作原理。

this的綁定問題

引用一點點其他知識點:一個方法的內部上下文this如何確定?

一個方法的調用分爲一下四種:

  1. 方法直接調用,稱之爲函數調用,當前的上下文this,綁定在全局的window上,在嚴格模式use strict下,thisnull
  2. 方法作爲一個對象的屬性,這個是否通過對象調用方法,this綁定在當前對象上。如下:

    let dog = {
        name: '八公',
        sayName: function() {
            console.log(this.name)
        }
    }
    dog.sayName() // 八公
    
  3. applycall調用模式,當前的方法的上下文爲方法調用的一個入參,如下:

    function sayHello() {
        console.log(this.hello)
    }
    
    let chineseMan = {
        hello: '你好啊'
    }
    sayHello.apply(chineseMan) // 你好啊
    
    let englishMan = {
        hello: 'how are you'
    }
    sayHello.apply(englishMan) // how are you
    
  4. 構造函數的調用,當前方法的上下文爲新生的實例,如下

    // 聲明構造函數
    function Animal(name) {
        this.name = name
        this.sayName = function() {
            console.log(this.name)
        }
    }
    
    let dog = new Animal('dog')
    dog.sayName() // dog
    
    let cat = new Animal('cat')
    cat.sayName() // cat
    

正文

apply實現

思路:apply方法實現在Function.prototype中

  1. 獲取到當前調用方法體
  2. 獲取方法的入參
  3. 綁定方法體中的上下文爲傳入的context--使用的方法就是對象調用屬性方法的方式綁定
  4. 調用方法

    Function.prototype.myApply = function() {

    let _fn = this
    if (typeof _fn !== 'function') {
        throw new TypeError('error')
    }
    let ctx = [...arguments].shift()
    // 因爲apply的入參是數組,所有只需要取第一個
    let args = [...arguments].slice(1).shift()
    ctx.myApplyFn = _fn
    // 由於apply會將原方法的參數用數組包裹一下,所以需要展開參數
    let res = ctx.myApplyFn(...args)
    delete ctx.myApplyFn
    return res

    }

call實現

思路:實現在Function.prototype中,大致和apply相似,卻別在對於參數的處理上

  1. 獲取到當前調用方法體
  2. 獲取方法的入參
  3. 綁定方法體中的上下文爲傳入的context
  4. 調用方法

    Function.prototype.myCall = function() {

    let _fn = this
    if (typeof _fn !== 'function') {
        throw new TypeError('error')
    }
    let ctx = [...arguments].shift()
    // call使用的多個入參的方式,所有直接取參數第二個參數開始的所有入參,包裝成一個數組
    let args = [...arguments].slice(1)
    ctx.myCallFn = _fn
    let res = ctx.myCallFn(...args)
     delete ctx.myCallFn
     return res

    }

bind實現

思路:實現在Function.prototype中,並且返回一個已經綁定了上下文的函數。利用閉包可以捕獲函數上下文的變量來實現,總體上比起之前兩個方法稍微複雜一些。

  1. 獲取調用bind的實例方法體
  2. 獲取需要綁定的上下文context
  3. 聲明閉包函數
  4. 閉包函數中綁定context到實例方法體中
  5. 閉包函數中調用原來的方法體
  6. 返回閉包函數

    Function.prototype.myBind = function() {
        let _fn = this
        if (typeof _fn !== 'function') {
            throw new TypeError('error')
        }
        let ctx = [...arguments].shift()
        let args = [...arguments].slice(1)
        return function() {
            // 因爲bind的調用方式,會有bind({}, 'para1', 'para2')('para3', 'para4'),這個時候需要將外面參數和內部參數拼接起來,之後調用原來方法
            args = args.concat([...arguments])
            ctx.myBindFn = _fn
            let res = ctx.myBindFn(...args)
            delete ctx.myBindFn
            return res
        }
    }
    

codepen演示 需要翻牆
<p class="codepen" data-height="265" data-theme-id="0" data-default-tab="js,result" data-user="beyondverage0908" data-slug-hash="PXMyqB" style="height: 265px; box-sizing: border-box; display: flex; align-items: center; justify-content: center; border: 2px solid black; margin: 1em 0; padding: 1em;" data-pen-title="rewrite bind">
<span>See the Pen
rewrite bind
by avg (@beyondverage0908)
on CodePen.</span>
</p>
<script async src="https://static.codepen.io/ass...;></script>

new 方法實現

思路:需要明白new到底做了什麼

  1. 生成一個新的實例對象
  2. 實例對象__proto__鏈接到構造函數的prototype對象
  3. 綁定構造函數的上下文爲當前實例
  4. 獲取參數,傳入參數,並調用構造函數

    function newObj() {

    let _o = {}
    let constructor = [...arguments].shift()
    let args = [...arguments].slice(1)
    if (typeof constructor !== 'function') {
        throw new TypeError('error')
    }
    _o.__proto__ = constructor.prototype
    
    // 第一種調用方式:藉助apply,call,或者bind實現綁定_o
    // constructor.apply(_o, args)
    
    // 第二種,使用屬性方法綁定的方式
    _o.myNewFn = constructor
    _o.myNewFn(...args)
    delete _o.myNewFn
    return _o

    }

    // how to use - 如何使用
    function Animal(name, weight) {

    this.name = name
    this.weight = weight

    }

    let dog = newObj(Animal, 'dog', '18kg')
    // the animal name: dog weight: 18kg
    console.log(the animal name: ${dog.name} weight: ${dog.weight})

    let cat = newObj(Animal, 'cat', '11kg')
    // the animal name: cat weight: 11kg
    console.log(the animal name: ${cat.name} weight: ${cat.weight})

codepen需要翻牆

<p class="codepen" data-height="265" data-theme-id="0" data-default-tab="js,result" data-user="beyondverage0908" data-slug-hash="MZNPoK" style="height: 265px; box-sizing: border-box; display: flex; align-items: center; justify-content: center; border: 2px solid black; margin: 1em 0; padding: 1em;" data-pen-title="MZNPoK">
<span>See the Pen
MZNPoK
by avg (@beyondverage0908)
on CodePen.</span>
</p>
<script async src="https://static.codepen.io/ass...;></script>

結語

熟悉函數內部的實現,瞭解內部的原理,對理解運行會有很多好處,親自實現一遍會給你很多領悟。同時這些知識點又是非常重要的。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章