Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I already know that apply and call are similar functions which set this (context of a function).

(我已经知道applycall是用于设置this相似函数(函数的上下文)。)

The difference is with the way we send the arguments (manual vs array)

(区别在于我们发送参数的方式(手动vs数组))

Question:

(题:)

But when should I use the bind() method ?

(但是我什么时候应该使用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));

jsbin

(jsbin)

  ask by Royi Namir translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
430 views
Welcome To Ask or Share your Answers For Others

1 Answer

Use .bind() when you want that function to later be called with a certain context, useful in events.

(当您希望以后在特定上下文中调用该函数时,请使用.bind() ,在事件中很有用。)

Use .call() or .apply() when you want to invoke the function immediately, and modify the context.

(若要立即调用该函数并修改上下文,请使用.apply() .call().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.

(调用/应用立即调用该函数,而bind返回一个函数,该函数稍后执行时,将具有正确的上下文集来调用原始函数。)

This way you can maintain context in async callbacks and events.

(这样,您可以在异步回调和事件中维护上下文。)

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.

(我在Node.js中将它广泛用于异步回调,我想为其传递成员方法,但仍希望上下文成为启动异步操作的实例。)

A simple, naive implementation of bind would be like:

(一个简单,简单的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 .

(它还有更多的功能(就像传递其他args一样),但是您可以阅读更多有关它的内容,并查看MDN上的实际实现。)

Hope this helps.

(希望这可以帮助。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...