2009-03-16 7 views
1

저는 Diaz의 저서 Pro JavaScript Design Patterns를 읽었습니다. 훌륭한 책. 나는 나 자신을 프로가 아니다. 내 질문 : 개인 인스턴스 변수에 액세스 할 수있는 정적 함수를 사용할 수 있습니까? 내 프로그램에는 여러 개의 장치가 있고 하나의 출력은 다른 장치의 입력에 연결할 수 있습니다. 이 정보는 입력 및 출력 배열에 저장됩니다. 내 코드는 다음과 같습니다.자바에서 개인 인스턴스 변수에 액세스하는 정적 public 메서드

var Device = function(newName) { 
    var name = newName; 
    var inputs = new Array(); 
    var outputs = new Array(); 
    this.getName() { 
     return name; 
    } 
}; 
Device.connect = function(outputDevice, inputDevice) { 
    outputDevice.outputs.push(inputDevice); 
    inputDevice.inputs.push(outputDevice); 
}; 

//implementation 
var a = new Device('a'); 
var b = new Device('b'); 
Device.connect(a, b); 

Device.connect에 장치 출력 및 입력 배열에 대한 액세스 권한이 없으므로 작동하지 않는 것 같습니다. Device에 pushToOutputs와 같은 비공개 메소드를 추가하지 않고 해당 장치를 노출 할 수있는 방법이 있습니까?

감사합니다. 스티브.

답변

2

Eugene Morozov가 맞습니다. 함수에서 함수를 직접 생성하면 해당 변수에 액세스 할 수 없습니다. 내 평소 접근법은 변수를 this으로 지정하고 이름을 지어서 개인용으로 지정해야합니다.

var Device = function(newName) { 
    this._name = newName; 
    this._inputs = new Array(); 
    this._outputs = new Array(); 
    this.getName() { 
     return this._name; 
    } 
}; 
Device.connect = function(outputDevice, inputDevice) { 
    outputDevice._outputs.push(inputDevice); 
    inputDevice._inputs.push(outputDevice); 
}; 

//implementation 
var a = new Device('a'); 
var b = new Device('b'); 
Device.connect(a, b); 
1

클로저를 만들면 권한있는 메서드를 사용하는 경우를 제외하고는 외부에서 클로저 변수에 액세스 할 수 없습니다.

솔직히 개인 변수에 대한 필요성을 느끼지 못했습니다. 특히 자바 스크립트 코드에서. 그래서 나는 그들을 귀찮게하지 않고 대중에게 공개 할 것이지만 그건 내 의견이다.

관련 문제