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

前端 未结 2 1265
梦如初夏
梦如初夏 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: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.

提交回复
热议问题