[英]How to write a replacement for a build-in prototype?
I'm using a Javascript interpreter which seems to provide a buggy Array.prototype.sort
and I'd like to replace it (at least for test purposes). 我正在使用一个Javascript解释器,它似乎提供了一个有问题的
Array.prototype.sort
并且我想替换它(至少出于测试目的)。
I've got a function mySort(array, comparator)
, but how can I make it to a function working like array.sort(comparator)
? 我有一个函数
mySort(array, comparator)
,但是如何使它像array.sort(comparator)
一样工作呢?
I also need to provide a default comparator, does a simple return a<b ? -1 : a>b ? +1 : 0
我还需要提供一个默认的比较器,是否简单
return a<b ? -1 : a>b ? +1 : 0
return a<b ? -1 : a>b ? +1 : 0
return a<b ? -1 : a>b ? +1 : 0
suffice? return a<b ? -1 : a>b ? +1 : 0
就足够了吗?
And there may be more problems I'm unaware of? 可能还有更多我不知道的问题?
A side question: My simple sorting works, but I'd gladly replace it by some well tested code. 附带的问题:我的简单排序有效,但是我很乐意用一些经过良好测试的代码替换它。
Array.prototype.sort=function(comp){ return mySort(this,comp);};
Or using custom arrays: 或使用自定义数组:
myArray=Object.create(Array.prototype);
myArray.sort=function(comp){ return mySort(this,comp);};
example=Object.create(myArray);
example.push(1,2);
example.sort();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.