3

Please consider this code in javascript:

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

I want to add a method for Groups property of the Selector class and use it for any instance. How can i do this?

Please be aware that i write this code:

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();

But when i set Group property i get error for calling method:

Error: selector.Groups.myFunction is not a function

I prefer to find a way using prototype object.

Thanks.

4

2 回答 2

1

当你说:

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

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

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

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

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

请参阅此链接以了解对数组子类化的 iframe hack。

于 2012-08-13T08:59:08.677 回答
1

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

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();

演示

但我不建议你使用这种做法。更好的是创建一个类 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();

​<a href="http://jsfiddle.net/f0t0n/6gRCH/2/" rel="nofollow">演示

于 2012-08-13T08:52:47.710 回答