this 與 call() / apply() / bind()


Posted by hoyi-23 on 2021-08-12

在JavaScript中,this的指向有五個重點:

  1. this 一般來說,不在乎位置,要看它是如何被呼叫的。
  2. 透過call() / apply() / bind() 指定 this
  3. 箭頭函式中的this,指向是全域。
  4. DOM 的 this 會綁定
  5. Simple Call(立即函式、CallBack Function、Clousure)的this,指向是全域。

call()

fn.call(this,para1,para2...)

使用call執行函式,第一個參數是指this的地方,後面才是函式的參數。
call會立刻執行,回傳function執行結果

apply()

fn.call(this,[para1,para2...])

apply 和 call 類似,只是後面的參數要用陣列表示,apply 只允許兩個變數傳入。
回傳function執行結果

bind()

var fn2 = fn.bind(this,,para1,para2...);
fn2();

fn.bind(this,,para1,para2...); 回傳的是綁定 this 後的原函數。
所以bind不會立刻執行,需要再去調用它。


範例:

var obj = {
  x: 81,
  getX: function() {
    return this.x;
  }
};

alert(obj.getX.bind(obj)());
alert(obj.getX.call(obj));
alert(obj.getX.apply(obj));

什麼時候要用bind呢?

我自己的想法是,bind和其他倆者不同的是,它可以先綁定好this,之後再執行。

Use .bind() when you want that function to later be called with a certain context, useful in events.
Use .call() or .apply() when you want to invoke the function immediately, and modify the context.


#call #apply #bind







Related Posts

Angular17 部屬完成,在瀏覽器中使用 F5 重新整理跳轉 404 異常解決

Angular17 部屬完成,在瀏覽器中使用 F5 重新整理跳轉 404 異常解決

ASP.NET Core Web API 入門教學 - 序

ASP.NET Core Web API 入門教學 - 序

Advanced JS  (上)

Advanced JS (上)


Comments