2012-08-10 55 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

相關問題