在另一个排序函数中调用自定义array.sort函数

时间:2014-08-18 14:39:22

标签: javascript scope

有没有办法可以做到这一点?在下面的代码段中,thissortByName内调用时无法访问sortByLyncStatus FN

原型定义:

sortByName: function (bud, light) {
  if (bud.FullName < light.FullName)
    return -1;
  if (bud.FullName > light.FullName)
    return 1;
  return 0;
},

sortByLyncStatus: function (chuck, norris) {
  if (chuck.LyncAvailability == "Available" && norris.LyncAvailability == "Available") {
    return this.sortByName(chuck, norris);
  }
  else {
    if (chuck.LyncAvailability == "Available")
      return -1;
    if (norris.LyncAvailability == "Available")
      return 1;
    else { // both are away, inactive, offline, or out of office
      var chuckLastActive = $.toDateFromJson(chuck.LyncLastActive);
      var norrisLastActive = $.toDateFromJson(norris.LyncLastActive);
      if (chuckLastActive < norrisLastActive)
        return 1;
      if (chuckLastActive > norrisLastActive)
        return -1;

      return this.sortByName(chuck, norris);
    }
  }
}

溶液

some.prototype.obj = {

  sortByName: function (a, b) {
    // omitted for solution
  },

  sortByLyncStatus: function(a, b) {
    // compare cases

    // default to name comparison
    return some.prototype.obj.sortByName(a, b);
  }
}

1 个答案:

答案 0 :(得分:1)

this将引用大多数种类的窗口。除非您将sortByName定义为全局函数,否则它不会作为this上的方法存在。

您可以将其定义为函数而不是方法,并直接调用它,如下所示:

var sortByName = function(a,b){};

var sortByLyncStatus = function(a,b){
    return sortByName(a,b);
}