【问题标题】:How to create method for an array as a property of an object in javascript?如何为数组创建方法作为javascript中对象的属性?
【发布时间】:2026-02-03 08:50:01
【问题描述】:

请在 javascript 中考虑此代码:

function Selector() {
    this.Status = "";
    this.Groups = new Array();
    this.Errors = new Array();
}

我想为 Selector 类的 Groups 属性添加一个方法并将其用于任何实例。我该怎么做?

请注意我写了这段代码:

function Selector() {
    this.Status = "";
    this.Groups = []; 
    this.Groups.myFunction = function(){alert(this.length);  
    };
    this.Errors = [];
}

var selector = new Selector();
selector.Groups = [1,2,3];
selector.Groups.myFunction();

但是当我设置 Group 属性时,调用方法会出错:

错误:selector.Groups.myFunction 不是函数

我更喜欢找到使用原型对象的方法。

谢谢。

【问题讨论】:

  • this.Groups.myFunction = function(){};.

标签: javascript oop object methods prototype


【解决方案1】:

当你说:

  selector.Groups = [1,2,3];
  selector.Groups.myFunction();

您实际上是在初始化一个新数组并将其存储在 selector.Groups 属性中,并且由于 Array 对象没有名为 myFunction 的方法,因此您会收到错误。

您可以扩展 Array 对象,以便每个数组都有一个 myFunction 方法,如下所示:

  Array.prototype.myFunction = function() { alert(this.length) };

这不是一个好主意 imo,但你没有很多选择,因为子类化数组不会保持 IE 中的长度属性:(

请参阅 this link 了解对数组子类化的 iframe hack。

【讨论】:

  • 非常感谢您的回复。
【解决方案2】:

您的代码不会以这种方式工作,因为在构造函数中,您将一个对象(数组)分配给类属性并扩展该特定实例。然后,当您分配新数组时,新创建的数组没有这样的方法。所以你的解决方案可以这样改变:

function Selector() {
    this.Status = "";
    this.setGroups([]);
    this.Errors = [];
}

Selector.prototype.myFunction = function() {
    alert(this.length);
};

Selector.prototype.setGroups = function(groups) {
    this.Groups = groups;
    this.Groups.myFunction = this.myFunction;
};

var selector = new Selector();
selector.Groups.myFunction();
selector.setGroups([1,2,3]);
selector.Groups.myFunction();
selector.setGroups(['foo', 'bar']);
selector.Groups.myFunction();

DEMO

​但我不建议您使用这种做法。 更好的是创建一个类 GroupCollection 并将一个数组封装为它的属性:

function GroupCollection(items) {
    this.items = items || [];
}

GroupCollection.prototype.myFunction = function() {
    alert(this.items.length);
};

function Selector() {
    this.Status = "";
    this.Groups = new GroupCollection();
    this.Errors = [];
}

Selector.prototype.setGroups = function(groups) {
    this.Groups.items = groups;
};

var selector = new Selector();
selector.Groups.myFunction();
selector.setGroups([1,2,3]);
selector.Groups.myFunction();
selector.setGroups(['foo', 'bar']);
selector.Groups.myFunction();

DEMO

【讨论】:

  • 非常感谢您的回复。