2009-04-29 3 views
0

어떻게 마스터 세부 정보 클래스를 구현하는 자바 스크립트에서 함수를 찾으려면?

 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; 
} 

그리고 내가 그것을 CategoryId주고이 범주 ID,
모든 항목 개체를 반환합니다 Item 클래스에 대한 함수를 작성하고 싶습니다. 가장 좋은 방법은 무엇을할까요? 그?

답변

1

....

내가 항목 프로토 타입 ( note that there are no classes in javascript)가 될 것이라고 생각 것, 그리고 이런 식으로 뭔가 보일 것

:

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 
관련 문제