When to use .bind() in JS

后端 未结 3 1933
花落未央
花落未央 2020-12-06 12:49

There is a ton of blogs and posts about how to use bind() and how it\'s different than call() and apply(), but there is very little ex

3条回答
  •  隐瞒了意图╮
    2020-12-06 13:33

    This is possibly the simplest way to explain it in a practical sense. Since most answers have given a theoretical definition and explanation, I will show a straightforward use case. You would use bind when you want to the function being called to have a different this value than the default one.

    var NS = {
      user     : "self",
      getUser  : function() { return this.user; }
    };
    
    var CLOSURE = NS.getUser;
    
    // error user is undefined, "this" in that context refers to the global object, "window"
    console.log(CLOSURE());
    
    // Bind the function call to NS object
    console.log(CLOSURE.bind(NS)());
    

    http://jsfiddle.net/ev3z3td3/2/

提交回复
热议问题