JavaScript 的上下文 “排序” 比较函数

Context of JavaScript compare function of "sort"

本文关键字:比较 函数 排序 上下文 JavaScript      更新时间:2023-09-26

在我的"class"方法中,我使用JavaScript"sort"函数和一个比较函数:

this.models.sort(this.comparator);

当排序函数调用我的比较器时,是否可以定义上下文/"this"比较器?

我知道可以这样做:

var self = this;
this.models.sort(function(a, b){return self.comparator.call(self, a, b);});

但是有人知道更简单的方法吗?

提前非常感谢

您可以使用绑定:

 this.models.sort(this.comparator.bind(this));

bind构建一个新的绑定函数,该函数将使用您传递的上下文执行。

由于这与IE8不兼容,因此通常采用闭合解决方案。但是你可以让它更简单:

var self = this;
this.models.sort(function(a, b){return self.comparator(a, b);});
您可以使用

bind来执行此操作:

this.models.sort(this.comparator.bind(context));