LeetCode JavaScript 30 Days Challenge – Day26 – 2693. Call Function with Custom Context

    LeetCode JavaScript 30 Days Challenge

    Enhance all functions to have the callPolyfill method. The method accepts an object obj as it’s first parameter and any number of additional arguments. The obj becomes the this context for the function. The additional arguments are passed to the function (that the callPolyfill method belongs on).

    強調所有的函式具有 callPolyfill 方法。該方法接受一個物件 obj 作為它的第一個參數和任意數量的附加參數。
    obj 將變成函式的上下文,附加參數被傳遞給函式。(屬於 callPolyfill 方法。
    

    For example if you had the function:

    function tax(price, taxRate) {
      const totalCost = price * (1 + taxRate);
      console.log(`The cost of ${this.item} is ${totalCost}`);
    }
    Calling this function like tax(10, 0.1) will log "The cost of undefined is 11". This is because the this context was not defined.
    

    However, calling the function like tax.callPolyfill({item: “salad”}, 10, 0.1) will log “The cost of salad is 11”. The this context was appropriately set, and the function logged an appropriate output.
    Please solve this without using the built-in Function.call method.

    但是,呼叫函式像是 tax.callPolyfill({item: "salad"}, 10, 0.1) 之類的函式將紀錄 “The cost of salad is 11” 的結果。
    this 上下文以作適當的設定,函式紀錄了適當的輸出。
    請在不使用內建 Function.call 方法的情況下解決此問題。
    

    Example 1:

    Input:
    fn = function add(b) {
      return this.a + b;
    }
    args = [{"a": 5}, 7]
    Output: 12
    

    Example 2:

    Input: 
    fn = function tax(price, taxRate) { 
     return `The cost of the ${this.item} is ${price * taxRate}`; 
    }
    args = [{"item": "burger"}, 10, 1,1]
    Output: "The cost of the burger is 11"
    

    solution:
    建立 function.prototype 來定義一個叫做 callPolyfill 的函式,
    將函式中的 this 來指向呼叫的陣列,同時用 apply 的方法來將參數 context 、
    運用展開運算子的第二個參數依序放入後回傳結果。
    當我們呼叫函式 function.prototype 時,會將參數通過函式內部的 this 傳遞物件的內容。

    Code 1: BigO(n)

    Function.prototype.callPolyfill = function(context, ...args) {
        // return this.bind(context)(...args)
        return this.apply(context, args);
    }
    

    FlowChart:
    Example 1

    var fn = function add(b) {
      return this.a + b;
    }
    
    console.log(fn.callPolyfill({ "a": 5 }, 7)); //12
    

    Example 2

    var fn = function tax(price, taxRate) { 
     return `The cost of the ${this.item} is ${price * taxRate}`; 
    }
    
    console.log(fn.callPolyfill({"item": "burger"}, 10, 1,1))
    //The cost of the burger is 10