覆盖 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]
Updated 是已经排序的数组。
不管我在customSort中return怎么设置,数组的顺序还是原来的顺序。如何覆盖 'this' 值/让它以正确的顺序指向数组?
如果您考虑上面给出的实际代码,则必须确保您的 customSort
函数更新 this
。
一种情况是customSort
只使用this
作为"read-only"输入,即-只把排序后的数组放在updated
,而不是改变[=12] =].
在这种情况下,考虑到上面的代码(您可能已经用它执行了测试),没有 updated
参数被发送到函数,以接收排序后的值。
另一种情况是customSort
returns排序后的数组,这种情况下你要收集它:
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;
我发现原生 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]
Updated 是已经排序的数组。
不管我在customSort中return怎么设置,数组的顺序还是原来的顺序。如何覆盖 'this' 值/让它以正确的顺序指向数组?
如果您考虑上面给出的实际代码,则必须确保您的 customSort
函数更新 this
。
一种情况是customSort
只使用this
作为"read-only"输入,即-只把排序后的数组放在updated
,而不是改变[=12] =].
在这种情况下,考虑到上面的代码(您可能已经用它执行了测试),没有 updated
参数被发送到函数,以接收排序后的值。
另一种情况是customSort
returns排序后的数组,这种情况下你要收集它:
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;