2012-08-16 2 views
0

JavaScript로 클래스를 정의하는 방법을 찾고있었습니다. 나는 하이브리드 모듈과 프로토 타입 패턴을 생각해 냈지만 뭔가 놓치지 않을 지 확신하지 못했다. 기본적으로 'this'키워드를 사용하고 싶었습니다. 예 :모듈 패턴을 사용한 JavaScript 클래스 프로토 타이핑

var A = function() 
    { 
    this.x = 10; 
    }; 

A.prototype = (function() 
    { 
    function privatePrint() 
     { 
     alert("Printing from private! x:" + this.x); 
     } 
    this.print = function() 
     { 
     privatePrint.call(this); 
     }; 
    return this; 
    }).apply(A.prototype); 

var a = new A(); 
a.print(); 

반환 값은 가독성을위한 것입니다. 처음에는 A.prototype을 사용할 수 있습니다.

패턴 나는 또한 시도 :

  • 모듈 : '새로운'키워드를 사용할 수 없습니다.
  • 프로토 타입, 프로토 타입 공개 : 을 민간 기능 프로토 타입 선언에 (객체에 의해 반환 된 public 메소드)

내 접근이 허용을 선언하면 더 확장?

+0

어떻게 접근법이 유용 할 지 모르겠지만 이점은 무엇입니까? 혼란스러워 보입니다. 왜 그냥'A.prototype = {...}'.. – elclanrs

+0

프로토 타입을 설정하고 객체를 설정 한 후에는 동일한 작업을 사용하여 그것을 확장 할 수 없습니다. – lietus

답변

0
**Public** 

function Constructor(...) { 
    this.membername = value; 
} 
Constructor.prototype.membername = value; 

**Private** 

function Constructor(...) { 
    var that = this; 
    var membername = value; 
    function membername(...) {...} 

} 

Note: The function statement 

function membername(...) {...} 

is shorthand for 

var membername = function membername(...) {...}; 

**Privileged** 

function Constructor(...) { 
    this.membername = function (...) {...}; 
} 
+0

의도적으로 생성자에서 메서드 선언을 피하는 것은 모든 새로운 인스턴스에 대해 만들어지기 때문입니다. – lietus

+0

추가 정보 : http://blog.thejit.org/2010/10/10/javascript-class-performance/ 생성자 성능의 개인 함수가 ~ 98 % 나 더 나쁨 – lietus

0

당신이 물어 본 지 2 년이 지났지 만 비슷한 방식으로 인터넷 검색을하면서 여기서 끝났습니다. 나는 IIFE에 가져 오기로 프로토 타입을 전달하는 이유가 혼란스러워 보이는 것처럼 본질적으로 의견을 묻고 있기 때문에 구현 이외의 단점을 보지 못한다. 또한 유사한

(function (NS) { 

    'use strict'; 

    // constructor for the Person "Class", attached to your global namespace 
    var Person = NS.Person = function (name) { 
     // set properties unique for each instance 
     this.name = name; 
    }; 

    // may not be necessary, but safe 
    Person.prototype.constructor = Person; 

    // private method 
    var _privateMethod = function() { 
     // do private stuff 
     // use the "_" convention to mark as private 
     // this is scoped to the modules' IIFE wrapper, but not bound the returned "Person" object, i.e. it is private 
    }; 

    // public method 
    Person.prototype.speak = function() { 
     console.log("Hello there, I'm " + this.name); 
    }; 

    return Person; 

})(window.NS = window.NS || {}); // import a global namespace 

// use your namespaced Person "Class" 
var david = new NS.Person("David"); 
david.speak(); 

있다

:

그렇지 않으면, 당신이있어하는 것은 내가 같은 본질적으로 본 것 "밝히려 프로토 타입 패턴"의 다른 "표준"구현과 매우 유사합니다 모듈 패턴은 구조는의 "클래스"구현과 같은 더있을 당신은 후 :

(function (NS) { 

    'use strict'; 

    // constructor for the Person "Class", attached to your global namespace 
    var Person = NS.Person = function (name) { 

     // reset constructor (the prototype is completely overwritten below) 
     this.constructor = Person; 

     // set properties unique for each instance 
     this.name = name; 
    }; 

    // all methods on the prototype 
    Person.prototype = (function() { 

     // private method 
     var _privateMethod = function() { 
      // do private stuff 
      // use the "_" convention to mark as private 
      // this is scoped to the IIFE but not bound to the returned object, i.e. it is private 
     }; 

     // public method 
     var speak = function() { 
      console.log("Hello there, I'm " + this.name); 
     }; 

     // returned object with public methods 
     return { 
      speak: speak 
     }; 
    }()); 

})(window.NS = window.NS || {}); // import a global namespace 

// use your namespaced Person "Class" 
var david = new NS.Person("David"); 
david.speak(); 

요점 : https://gist.github.com/dgowrie/24fb3483051579b89512

관련 문제