如何编写内置原型的替代品?

时间:2017-05-11 15:17:07

标签: javascript arrays sorting prototype

我正在使用Javascript解释器,它似乎提供了一个bug Array.prototype.sort,我想替换它(至少是为了测试目的)。

我有一个函数mySort(array, comparator),但我如何才能使它成为像array.sort(comparator)这样的函数?

我还需要提供一个默认比较器,只需要一个简单的return a<b ? -1 : a>b ? +1 : 0吗?

可能还有更多我不知道的问题?

一个附带问题:我的简单排序有效,但我很乐意用经过严格测试的代码替换它。

1 个答案:

答案 0 :(得分:3)

Array.prototype.sort=function(comp){ return mySort(this,comp);};

或使用自定义数组:

myArray=Object.create(Array.prototype);
myArray.sort=function(comp){ return mySort(this,comp);};

example=Object.create(myArray);
example.push(1,2);
example.sort();