access outer “this” in Javascript sort method

The different this is because the the anonymous function (its own closure) called by arr.sort calls the function with this being set to a different item than your main object. In an Array.sort, I am not actually sure what this is set to, but it is probably the Array you are sorting. A normal work around in this situation is to use another variable:

function some_object(...) {
   var so = this; // so = current `this`
   this.data = {...};

   this.do_something = function(...) {
      var arr = [...];

      arr.sort(function (a, b) {
         return so.data[a] - so.data[b];
      });  
   }
}

Leave a Comment