簡體   English   中英

覆蓋array.prototype中的this值

[英]Overwrite the this value in array.prototype

我發現原生js排序功能有時會搞砸,所以我想實現自己的功能。 可以說我有以下內容:

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

數組應為[2、3、5、6]

已更新的是已排序的數組。

不管我在customSort中返回什么,數組的順序仍然是原始順序。 如何覆蓋“ this”值/使其以正確的順序指向數組?

如果考慮上面給出的實際代碼,則必須確保您的customSort函數更新了this

一種情況是customSortthis作為“只讀”輸入使用,即-僅將已排序的數組置於updated ,而不是更改this 在這種情況下,考慮到上面的代碼(您可能已經使用其進行過測試),則不會將任何updated參數發送到該函數以接收排序后的值。

另一種情況是customSort返回排序后的數組,在這種情況下,您必須收集它:

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

我剛剛結束了遍歷過updated陣列和更換的每個值this與價值updated 在代碼中,看起來像...

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

我希望該函數以與本機array.sort函數完全相同的方式進行操作-它會覆蓋提供的數組,而不是返回新的排序數組。

我覺得這很奇怪...您無法一次掃清整個this值,但可以逐步進行。 我無法在customSort函數中執行此操作:

this = updated;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM