Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

access outer "this" in Javascript sort method

Tags:

javascript

I have this code:

function some_object(...) {    this.data = {...};     this.do_something = function(...) {       var arr = [...];        arr.sort(function (a, b) {          return this.data[a] - this.data[b];       });      } } 

However it's not working I think because this cannot be accessed in sort - another this is seen there for some reason, not the this of enclosing outer object.

What to do? thanks

like image 419
zaharpopov Avatar asked Feb 15 '10 04:02

zaharpopov


People also ask

Which sorting algorithm does sort () method use in JavaScript?

JavaScript by default uses insertion sort for the sort() method. This means that it is not appropriate when sorting large data sets. When dealing with large data sets, one should consider other sorting algorithms such as merge sort.

How do you access outer this in JavaScript?

You can bind the "outer" instance to the "inner" function by invoking the bind method on the inner function. Learn more at MDN. Or use an arrow function. I see you answered in 2016 so that should be an option.


1 Answers

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];       });      } } 
like image 56
Doug Neiner Avatar answered Oct 03 '22 10:10

Doug Neiner