2010-07-12 7 views
5

자바 스크립트에서 oop을 사용하는 것이 비교적 새로운데 개인적인 방법이 가장 좋은 방법인지 궁금하네요. 지금 당장 mootools를 사용하여 클래스를 만들고 저는 밑줄로 접두어를 붙이고 클래스 밖에서 메서드를 호출하지 않도록함으로써 private 메서드를 시뮬레이트합니다. 그래서 내 수업은 다음과 같습니다 :Mootools 클래스의 private 메소드

var Notifier = new Class(
{ 
    ... 
    showMessage: function(message) { // public method 
     ... 
    }, 

    _setElementClass: function(class) { // private method 
     ... 
    } 
}); 

JS의 개인용 메소드를 처리하는 좋은 방법입니까 아니면 표준 방법입니까?

답변

12

MooTools는 기능에 대해 protect 메서드를 제공하므로 Class 외부에서 호출되지 않도록 보호하려는 모든 메서드에서 MooTools를 호출 할 수 있습니다. 그래서 당신은 할 수 있습니다 :

​var Notifier = new Class({ 
    showMessage: function(message) { 

    }, 
    setElementClass: function(klass) { 

    }.protect() 
})​; 

var notifier = new Notifier(); 
notifier.showMessage(); 
notifier.setElementClass(); 
> Uncaught Error: The method "setElementClass" cannot be called. 

은하지 않는 것이 class 자바 스크립트의 미래에 예약 된 키워드입니다 그것을 사용할 때 코드가 깨질 수 있습니다. 이 시점에서 Safari는 확실히 파손되지만 다른 브라우저의 동작도 보장되지 않으므로 class을 식별자로 사용하지 않는 것이 좋습니다.

protect을 사용하는 장점 중 하나는이 클래스를 확장해도 여전히 하위 클래스의 보호 된 메서드에 액세스 할 수 있다는 것입니다. 당신은 접두사 또는 방법 이전 또는 이후에 _ 접미로 명명 규칙을 사용하려면

Notifier.Email = new Class({ 
    Extends: Notifier, 

    sendEmail: function(recipient, message) { 
     // can call the protected method from inside the extended class 
     this.setElementClass('someClass'); 
    } 
}); 

var emailNotifier = new Notifier.Email(); 
emailNotifier.sendEmail("a", "b"); 
emailNotofier.setElementClass("someClass"); 
> Uncaught Error: The method "setElementClass" cannot be called. 

는, 그뿐만 아니라 완벽하게 괜찮아요. 또는 _과 보호 된 메소드를 결합 할 수도 있습니다.

+0

이것은 내가 찾던 바로 그 것이다. 감사합니다. 다음에 mootools 문서를 두 번 확인해야 할 것입니다. – aubreyrhodes

2

글쎄, 일관성을 유지하는 한 문제가 생기지 않을 것입니다.

폐쇄을 통해 자바 스크립트에서 진정한 사생활 보호를 위해 패턴이 있습니다. 모든 개체 (작은 메모리 풋 프린트) 사이의 상속과 공유하는 공용 메서드를 추가하려면

var Notifier = function() { 

    // private method 
    function setElementClass(class) { 
     //... 
    } 

    // public method 
    this.showMessage = function(message) { 
     // ... 
     setElementClass(...) // makes sense here 
    }; 
}; 

var noti = new Notifier(); 
noti.showMessage("something");  // runs just fine 
noti.setElementClass("smth else"); // ERROR: there isn't such a method 

, 당신은 객체의 프로토 타입에 추가해야합니다.

// another way to define public functions 
// only one will be created for the object 
// instances share this function 
// it can also be used by child objects 
// the current instance is accessed via 'this' 
Notifier.prototype.showMessage = function() { 
    // ... 
    this.otherPublicFunction(...); 
};​ 

는 난 단지 당신이 당신이 무슨 일을하는지 알 수있을 것입니다 때문에, 자바 스크립트에서 개체를 처리하는 원료 방법을 조사하는 것이 좋습니다. 클래스와 같은 Mootools는이 언어가 다른 언어와 다른 것을 숨기기에 좋을 것입니다. 그러나 진실은 다른 클래스 기반 OO 언어 에서처럼 class을 자바 스크립트로 말할 때 똑같은 것을한다고 생각하는 것이 순전히 순전히 다를 수 있다는 사실입니다.

관련 문제