iT邦幫忙

第 11 屆 iT 邦幫忙鐵人賽

DAY 25
1
Modern Web

從Stack Overflow學前端系列 第 25

從StackOverflow上學CODING(25) 甚麼時候用 call()& apply()& bind()

Javascript call() & apply() vs bind()?

I already know that apply and call are similar functions which set this (context of a function).
The difference is with the way we send the arguments (manual vs array)
Question:
But when should I use the bind() method ?

我已經知道如果我呼叫了一個類似於這個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));

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.

在你想要函式會在同樣的內容時再被呼叫時用 .bind() (在事件時很實用)
如果你想要函式馬上被執行而且可能會想更改內容用 .call() or .apply()

Call/apply call the function immediately, whereas bind returns a function that, when later executed, will have the correct context set for calling the original function. This way you can maintain context in async callbacks and events.

Call/apply會馬上呼叫函式,而bind會return一個函式等待稍後被執行,而且會有正確的內容被設為等待呼叫的原始函式,在這個情況下你可以在callbacks和事件下維護內容

I do this a lot:

function MyObject(element) {
    this.elm = element;

    element.addEventListener('click', this.onClick.bind(this), false);
};

MyObject.prototype.onClick = function(e) {
     var t=this;  //do something with [t]...
    //without bind the context of this function wouldn't be a MyObject
    //instance as you would normally expect.
};

I use it extensively in Node.js for async callbacks that I want to pass a member method for, but still want the context to be the instance that started the async action.
A simple, naive implementation of bind would be like:

我在Node.js 的async callbacks下很廣泛的應用這個方式,例如我想要傳遞一個member method但仍想要內容會觸發async action
譬如說,原生地應用bind會像這樣:

Function.prototype.bind = function(ctx) {
    var fn = this;
    return function() {
        fn.apply(ctx, arguments);
    };
};

There is more to it (like passing other args), but you can read more about it and see the real implementation on the MDN.

你可以在MDN看到更多實際應用:


上一篇
從StackOverflow上學CODING(24)為何 ◎ܫ◎或 ☺不能成為一個 JS變數名
下一篇
從StackOverflow上學CODING(26) setTimeout或 setInterval?
系列文
從Stack Overflow學前端30

尚未有邦友留言

立即登入留言