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
The different
thisis because the the anonymous function (its own closure) called byarr.sortcalls the function withthisbeing set to a different item than your main object. In an Array.sort, I am not actually sure whatthisis set to, but it is probably the Array you are sorting. A normal work around in this situation is to use another variable: