【问题标题】:Overwrite the this value in array.prototype覆盖 array.prototype 中的 this 值
【发布时间】:2015-12-29 01:52:45
【问题描述】:

我发现原生 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中返回什么,数组的顺序还是原来的顺序。如何覆盖“this”值/让它以正确的顺序指向数组?

【问题讨论】:

  • 搞砸了是什么意思? [5, 2, 3, 6].sort(function (a, b) { return a - b; }) 每次都能完美运行。
  • 我并不是说在这种情况下它搞砸了。我发现它没有正确排序的实例。我试图给出一个非常简单的示例,说明我希望 customSort 函数返回什么。我认为我在这一点上很清楚。
  • 你为什么不给出失败的实际例子呢?
  • 因为我认为您正在尝试解决您不需要的问题。我认为您使用 sort 错误。如果您提出您在sort 中遇到的实际 问题,我们可以解决该问题,因此您无需搞砸原型。这称为 XY 问题。当你应该解决 X 时,你却忙于解决 Y。

标签: javascript arrays sorting prototype this


【解决方案1】:

如果您考虑上面给出的实际代码,则必须确保您的 customSort 函数更新 this

一种情况是customSort 仅使用this 作为“只读”输入,即 - 仅将排序后的数组放入updated,而不是更改this。 在这种情况下,考虑到上面的代码(您可能已经执行过测试),没有updated 参数被发送到函数,以接收排序值。

另一种情况是customSort返回排序后的数组,这种情况下你必须收集它:

array = array.customSort(function(a,b) {return a - b});
console.log(array);

【讨论】:

    【解决方案2】:

    我刚刚遍历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;
    

    【讨论】:

      猜你喜欢
      • 2019-05-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多