我很好奇如何在 Array 对象上实现我自己的排序函数。忽略有关扩展/覆盖内置的所有常见警告/危险,请考虑以下情况:
Array.prototype.sort = function() {
this = mySortFunction(this);
function mySortFunction(arr) { ... };
};
在闭包内部,this
引用数组对象[number, number2, number3, etc.]
。如何重新分配this
作为内部排序功能的结果?可能吗?
您的解决方案似乎有点多余:
Array.prototype.sort = function() {
this = mySortFunction(this);
function mySortFunction(arr) {
arr = yetAnotherSortFunction(arr)
function yetAnotherSortFunction(arr2) {...}
// and so on...
};
};
如果你真的想这样做,为什么不首先直接引用你的数组:
Array.prototype.sort = function() {
// your implementation:
// for (var i = this.length, ...
// if (this[0] == ...
// this[i] = ...
// ...
};