Difference between function binding and closing in Javascript?

When we need to call the javascript function with the current context object, I see that there are two options:

  • Using the snap function
  • Using Javascript Closure

Function Binding Example

myProject.prototype.makeAjax = function() {
  $.get('http://www.example.com/todoItems', function success(items) {
   this.addItemsToList(items)
  }.bind(this));
}

JS closing example

myProject.prototype.makeAjax = function() {
  var that = this;

  $.get('http://www.example.com/todoItems', function success(items) {
   that.addItemsToList(items)
  });
}

I want to ask:

  • Which of the two is better in terms of performance?
  • What should be preferred when writing code?
+4
source share
1 answer

This probably depends a bit on what should be preferred. I am inclined to use the latter (although in fact I prefer the former, but some third-party libraries we use the restriction). I think the important thing when choosing a style is consistent.

prototype.bind , IE8 , .

, , , bind , , , , . jsperf, , .

, JSPerf . , , , ( ). , 7 . , .

var limit = 100000;

var a = {
   val: 0,
   do: function(i) { val = i; /* Actually do some work to ensure doesn't get optimised out */ }  
};

var b = {
   myFunc: function(callback) { callback(); /* Function that going to change this keyword */}   
};



var start = +new Date();

   for(var i = 0; i < limit; i++) {
     b.myFunc(function() {
        this.do(i);
     }.bind(a));
   };

var end =  +new Date();
var diff = end - start;
console.log("bind took " + diff + " ms");

var start = +new Date();

   for(var i = 0; i < limit; i++) {
     var that = a;
     b.myFunc(function() {
        that.do(i);
     });
   };

var end =  +new Date();
var diff = end - start;

console.log("closured took " + diff + " ms");
Hide result
+1

All Articles