2012-08-10 48 views
3

请在JavaScript考虑下面的代码:如何为一个数组作为在javascript对象的属性创建方法?

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

我想补充的方法为选择类组属性,并使用它的任何实例。我怎样才能做到这一点?

请注意,我写这篇文章的代码:

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

但是,当我设置组属性,收到错误调用方法:

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

我宁愿找使用原型对象的方式。

谢谢。

+2

'this.Groups.myFunction =函数(){};' – 2012-08-10 15:59:51

回答

1

当你说:

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

你实际上是初始化一个新的阵列和存储它在selector.Groups属性,因为数组对象没有一个名为myFunction的方法,你会得到一个错误。

你可以扩展Array对象,这样每个阵列有一个myFunction的方法,像这样:

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

这是不是一个好主意海事组织,但你不能因为继承的阵列具有许多选项留不会保持在IE :(

length属性见this link在iframe劈死阵列子类

+0

谢谢你你的回答太多了。 – Arman 2012-08-13 10:50:39

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

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

+0

非常感谢您的回复。 。 – Arman 2012-08-13 10:51:58

相关问题