2009-04-29 8 views
0

J'ai ce code:comment implémenter les classes de détails maîtres trouver une fonction en javascript?

function Item(id, itemType, itemData, itemCategoryId, itemRank) { 
    this.id = id; 
    this.itemType = itemType; 
    this.itemData = itemData; 
    this.itemCategoryId = itemCategoryId; 
    this.itemRank = itemRank; 
} 
function Category(id) { 
    this.id = id; 
} 

Et je veux écrire une fonction pour la classe d'objet que je lui donne la CategoryId et il retournera tous les articles objets avec cette id Catégorie,
Quelle est la meilleure façon de fais ça?

Répondre

1

Je ne vois pas .... tableau

Je suppose qu'il y aurait un prototype d'articles (note that there are no classes in javascript), et il ressemblerait à quelque chose comme ceci:

function Item(id, categoryId, data, rank) { 
    this.id = id; 
    this.categoryId = categoryId; 
    this.data = data; 
    this.rank = rank; 
} 

function Items() { 
    this.items = []; 
    this.findByCategory = function(categoryId) { 
    var result = []; 
    for(var i=0;i<this.items.length;i++) { 
     if (categoryId == this.items[i].categoryId) 
      result.push(this.items[i]); 
    } 
    return result; 
    } 
    this.add = function(id, categoryId, data, rank) { 
    this.items.push(new Item(id, categoryId, data, rank)); 
    } 
} 

var items = new Items(); 
items.add(2, 0, null, null); 
items.add(1, 1, null, null); // I'm not going to care about data and rank here 
items.add(2, 1, null, null); 
items.add(3, 1, null, null); 
items.add(4, 2, null, null); 
items.add(5, 3, null, null); 

var cat1 = items.findByCategory(1); 
alert(cat1); // you will get a result of 3 objects all of which have category 1 
Questions connexes