JavaScript - Binding

From NoskeWiki
Jump to: navigation, search

About

NOTE: This page is a daughter page of: JavaScript


JavaScript binding always messes me up... I don't do JavaScript quite often enough to know the flow well... so typically I'll have a loop, each one calling a function with a different index (or something different), yet they all come out the same... below is a nice example from this thread on what's happening:

Binding

A loop without binding:

var funcs = [];
for (var i = 0; i < 3; i++) {      // Let's create 3 functions
  funcs[i] = function() {          // ... and store them in funcs
    console.log("My value: " + i); // ... each should log its value.
  };
}
 
for (var j = 0; j < 3; j++) { funcs[j](); }      // Log values.
 
// Outputs: 3, 3, 3.  // BAD!


With binding:


function log(x) {
  console.log('My value: ' + x);
}
 
var funcs = [];
 
for (var i = 0; i < 3; i++) {
  funcs[i] = log.bind(this, i);
}
 
for (var j = 0; j < 3; j++) { funcs[j](); }      // Log values.
 
// Outputs: 0, 1, 2.  // GOOD.


See Also