2012-08-10 5 views
3

는 자바 스크립트 코드를 고려하십시오 :배열을 자바 스크립트에서 객체의 속성으로 만드는 방법은 무엇입니까?

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

내가 선택기 클래스 그룹 속성에 대한 방법을 추가 인스턴스를 위해 그것을 사용하려고합니다. 내가 어떻게 할 수 있니?

오류 : selector.Groups.myFunction 함수

하지

이 코드 쓰기 양해하여 주시기 바랍니다 :

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

을하지만 난이 그룹의 속성을 설정할 때 내가 방법을 호출하는 오류

프로토 타입 객체를 사용하는 방법을 찾는 것을 선호합니다.

감사합니다.

+2

'this.Groups.myFunction = 기능() {};. ' –

답변

1

는 말 :

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

당신은 실제로 새로운 배열을 초기화하고 저장하는 더 나은는 클래스 GroupCollection을 만들고 해당 속성으로 배열을 캡슐화하는 것입니다 selector.Groups 속성에 있고 Array 객체에는 myFunction이라는 메서드가 없으므로 오류가 발생합니다. IMO 좋은 생각이 아니다

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

을,하지만 당신은 배열을 서브 클래스 이후 많은 옵션 왼쪽하지 않는 :

모든 배열은 myFunction이 방법을 가질 수 있도록이 같은 배열 객체를 확장 할 수 배열 서브 클래 싱에 해킹 iframe을위한 this link를 참조

:(IE의 길이 속성을 유지하지 않습니다

+0

고맙습니다. ver. 귀하의 회신에 많이. – Arman

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

하지만 난 당신이 비록 같은 연습을 사용하지 않는 것이 좋습니다.

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

관련 문제