[英]Why can't I overwrite the prototype of `Array` (`Array.prototype`)?
[英]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
。
一种情况是customSort
仅this
作为“只读”输入使用,即-仅将已排序的数组置于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.