简体   繁体   中英

Overwrite the this value in array.prototype

I've found that the native js sort function screws up from time to time so I wanted to implement my own. Lets say i have the following :

Array.prototype.customSort = function(sortFunction, updated) {...}
var array = [5, 2, 3, 6]
array.customSort(function(a,b) {return a - b})
console.log(array)

Array should be [2, 3, 5, 6]

Updated is the array that has been sorted.

No matter what I return in customSort, the order of array is still in the original order. How do I overwrite the 'this' value / get it to point to the array with the correct order?

If you consider the actual code you gave above, you have to make sure that your customSort function updates this .

One case is that customSort only uses this as "read-only" input, that is - only puts the sorted array in updated , rather than changing this . In such case, considering the code above (which you might have performed tests with), no updated parameter is sent to the function, to receive the sorted values.

Another case is that customSort returns the sorted array, in which case you have to collect it:

array = array.customSort(function(a,b) {return a - b});
console.log(array);

I just ended up iterating over the updated array and replacing each value in this with the value in updated . In code, that looks like...

function customSort(cb) {
    ...//updated is the sorted array that has been built
    var that = this;
    _.each(updated, function (ele, index) {
        that[index] = ele;
    })
}

I wanted the function to operate in the exact same way the native array.sort function does - it overwrites the array provided instead of returning a new, sorted array.

I find it odd that this works... you cannot overwrite the entire this value in one clean sweep but you can in steps. I couldn't do this for in the customSort function :

this = updated;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM