在 javascript 中,每個函式都會是一個物件 function,它們包含了幾個預設的方法 bind()、call()及apply()

在這篇文章中,我們將介紹這幾個方法的使用

若有使用過 javascript,應該知道 this 這個關鍵字的相關用法,但有時候 this 會指向可能不是你所預想的物件,如這篇文章

以下這幾個方法主要是可以用在處理 this 所指向的物件


假設我們有一個 person 的物件,其中有 getFullName的方法,並且其中的 this 將指向 person

如:

var person={
    "firstName": "camel",
    "lastName": "chang",
    "getFullName": function()
        {
            return this.firstName+" "+this.lastName;
        }
};
  • bind()
    可以傳入一個參數,此參數將代表此函式中 this 所指向的物件。
    如:

    var logName=function(arg1, arg2)
    {
        console.log(this.getFullName());
    };
    // 預設 this 會指向 window,window 物件並無 getFullName 方法
    logName(arg1, arg2);
    // undefined
    logName.bind(person)(arg1, arg2)
    // camel chang
    

    因此我們可以看到上面使用了 bind() 以後,函式中 this 將被取代為 person 物件

  • call()
    跟 bind 很像,不過不需要再次 invoke 函式。在上面例子我們可以看到 bind() 完之後,我們還要再次 invoke 函式一次。
    如:

    var logName=function(arg1, arg2)
    {
        console.log(this.getFullName());
    };
    // 預設 this 會指向 window,window 物件並無 getFullName 方法
    logName(arg1, arg2);
    // undefined
    logName.call(person, arg1, arg2);
    // camel chang
    
  • apply()
    跟 call 很像,只差在參數部分要使用陣列。
    如:

    var logName=function(arg1, arg2)
    {
    console.log(this.getFullName);
    };
    // 預設 this 會指向 window,window 物件並無 getFullName 方法
    logName(arg1, arg2);
    // undefined
    logName.apply(person, [arg1, arg2]);
    // camel chang
    

接下來,我們來看看以上這三個方法實際使用的範例及用法

  • function borrowing
    相似的物件,共用方法。

    var person={
    "firstName": "camel",
    "lastName": "chang",
    "getFullName": function(){
    console.log(this.firstName+" "+this.lastName);
    }
    };
    // 假設有相似的物件
    var person2={
        "firstName": "penny",
        "lastName": "Li"
    };
    // 我們就可以共用 person的方法
    person.getFullName.bind(person2)();
    // penny Li
    
  • function carrying
    根據既有 function,更改其參數預設,達到複製或創造新函式。

    // 本來為兩數相乘的函式
    function multiply(a, b)
    {
        return a*b;
    }
    // 我們利用上面這個既有函式,創造一個固定乘2的函式
    var multiplyByTwo=multiply.bind(this, 2);
    console.log(multiplyByTwo(4));
    // 8
    

參考資料:

https://pjchender.blogspot.tw/2016/06/function-borrowingfunction-currying.html

Leave a Reply