Function.bind vs Closure in [removed] how to choose?

前端 未结 2 1258
梦如初夏
梦如初夏 2020-12-14 01:55

As said here:

http://jqfundamentals.com/book/index.html

Closures can also be used to resolve issues with the this keyword, which is unique t

相关标签:
2条回答
  • 2020-12-14 02:26

    Take a look at this line in the example in the link above

    console.log(self.myName, this.myName);
    

    (with self = this; a couple of lines above). The closure defined outerFunction method, exists in a different scope that is why it has a different this value from the outerObj object. (self.myName!=this.myName)

    Scope traversal means, when you are reaching to grab a value (variable,object) that exists in a different scope, therefore additional overhead is added (code becomes slower to execute).

    Using bind, you 're calling a function with an existing scope, so that scope traversal does not take place.

    0 讨论(0)
  • 2020-12-14 02:33

    What it's referring to are things like this

    obj.doSomething = function() {
      var that = this;
      setTimeout(function() {
        // this is the window
        // that is the obj
        that.doSomethingElse();
      }, 50);
    };
    

    vs

    obj.doSomething = function() {
      setTimeout((function() {
        // this is the obj
        this.doSomethingElse();
      }).bind(this), 50);
    };
    

    Benchmark. No noticable difference in chrome.

    0 讨论(0)
提交回复
热议问题