有没有一种方法可以组合函数并将它们添加到Javascript中的多个数组中?

有没有一种方法可以组合函数并将它们添加到Javascript中的多个数组中?,javascript,Javascript,我有以下代码: $scope.fetching = []; $scope.loading = []; $scope.fetching.start = function (activity) { var index = this.indexOf(activity); if (index == 0) this.push(activity) }; $scope.fetching.success = function (activity) { var index

我有以下代码:

$scope.fetching = [];
$scope.loading = [];
$scope.fetching.start = function (activity) {
    var index = this.indexOf(activity);
    if (index == 0)
        this.push(activity)
};
$scope.fetching.success = function (activity) {
    var index = this.indexOf(activity);
    if (index >= 0)
        this.splice(index, 1);
};
$scope.loading.start = function (activity) {
    var index = this.indexOf(activity);
    if (index == 0)
        this.push(activity)
};
$scope.loading.success = function (activity) {
    var index = this.indexOf(activity);
    if (index >= 0)
        this.splice(index, 1);
};
我在一个数组中存储正在加载的所有内容的列表,在另一个数组中存储正在获取的所有内容的列表。要使用这些代码,我需要编写如下代码:

$scope.fetching.start("Fetching new topics");
$scope.fetching.success("Fetching new topics");
$scope.loading.start("Loading new ideas");
$scope.loading.success("Loading new ideas");

是否有一种方法可以使我不必为获取和加载数组重复使用完全相同的代码?

如果支持非标准的
\uuuuuuu proto\uuuu
属性,您可以这样做():


由于数组/对象具有相同的结构,因此可以编写一个函数来构建该类型的对象

function buildModifiedArray() {
  var arr = [];
  arr.start = function (activity) {
    var index = this.indexOf(activity);
    if (index == 0)
        this.push(activity)
  };
  arr.success = function (activity) {
    var index = this.indexOf(activity);
    if (index >= 0)
        this.splice(index, 1);
  };
  return arr;
}

$scope.fetching = buildModifiedArray();
$scope.loading = buildModifiedArray();

你可以考虑为你的任务创建一个类:

function LoadArray() {
    // ...
}
LoadArray.prototype = [];
LoadArray.prototype.start = function (activity) {
    var index = this.indexOf(activity);
    if (index == 0)
        this.push(activity)
};
LoadArray.prototype.success = function (activity) {
    var index = this.indexOf(activity);
    if (index >= 0)
        this.splice(index, 1);
};

$scope.loading = new LoadArray();
$scope.fetching = new LoadArray();

如果您想知道的话,IE6也支持这一点。

$scope.load.start=$scope.fetching.start?当然。只需将相同的函数分配给两者。有什么问题吗?是的,谢谢。我将其更改为$scope.fetching start。您的代码看起来非常令人印象深刻。我使用的是IE9及以上版本,所以你的代码可以吗?@Alan:不幸的是没有,很遗憾。这是将其作为真正数组的唯一方法,同时能够为其定义原型,而不是分配给
数组。prototype
。也许提波斯的答案不会太糟糕。
function LoadArray() {
    // ...
}
LoadArray.prototype = [];
LoadArray.prototype.start = function (activity) {
    var index = this.indexOf(activity);
    if (index == 0)
        this.push(activity)
};
LoadArray.prototype.success = function (activity) {
    var index = this.indexOf(activity);
    if (index >= 0)
        this.splice(index, 1);
};

$scope.loading = new LoadArray();
$scope.fetching = new LoadArray();