2013-04-26 3 views
3

아마도 가능하지 않을 수도 있지만 궁금합니다. 공용 팩토리 메소드로 개인 생성자를 정의 할 수 있습니까?정적 멤버가 포함 된 Javascript의 개인 생성자

function MyParentClass() {} 
MyParentClass.prototype.init = function() { ... } 

function MyChildClass() {} 
MyChildClass.prototype = new MyParentClass(); 
MyChildClass.prototype.init = function() { 
    ... 
    MyParentClass.prototype.init.apply(this); 
    ... 
} 
MyChildClass.Create = function() { 
    var instance = new MyChildClass(); 
    instance.init(); 
    return instance; 
} 

두 생성자를 숨기고 Create() 만 노출 할 수 있습니까?

이 재정의 가능한 init() 접근 방식에 대한 다른 접근 방식도 환영합니다. 고맙습니다.

답변

8

달성하고자하는 것이 확실하지 않지만, MyClass이 인스턴스를 만들 수있는 공장 메서드 create을 가진 싱글 톤이되는 예제가 있습니다.

//MyClass will be an object with a create method only 
var MyClass = (function() { 
    function MyClass() { 
     this.initialized = false; 
    } 

    MyClass.prototype = { 
     init: function() { 
      this.initialized = true; 
      return this; 
     } 
    }; 

    return { 
     create: function() { 
      return new MyClass().init(); 
     } 
    }; 

})(); 

var m = MyClass.create(); 
console.log(m); 
console.log(m.constructor); //Will be Object because we replaced the whole prototype 

그러나, 나는 당신이 두 개의 생성자 함수 (initconstructor 자체를) 갖고 싶어 왜 확실하지 않다? 객체 생성 프로세스를 추상화하려는 것은 복잡하기 때문에 멀리하고 있습니까?

상속을 얻는 방법 때문에 constructor 논리를 다른 기능으로 단순히 옮기고 싶다고 생각합니다.

다음 작업을 수행 할 때 생성자 논리를 호출하지 않으려 고합니까?

MyChildClass.prototype = new MyParentClass(); 

그것은 문제 (이것은 오래된 브라우저에서 지원되지 않습니다 를 해결하는 것입니다 Object.create를 사용하는 경우라면,하지만 거기에 대한 심입니다 - 모든 심 지원 당신이 필요로하는 것이 특징은, 그러나 그 Object.create).

function A(test) { 
    this.test = test; 
} 

function B(test) { 
    A.call(this, test); //call parent constructor 
} 
B.prototype = Object.create(A.prototype); //inherit from A 

var b = new B('test'); 

console.log(b); 
console.log(b instanceof A); //true 

는 또한 new 키워드와 함께 constructor 기능을 사용하지 않고, 순수 프로토 타입 접근 방법을 사용할 수 있습니다.

var A = { 
     init: function (test) { 
      this.test = test; 
      return this; 
     } 
    }, 
    B = Object.create(A), 
    b; 

    //override constructor function 
    B.init = function (test) { 
     return A.init.call(this, test); 
    }; 

b = Object.create(B).init('test'); 

console.log(b); 
+0

나는 상속에 대한 토론이 OP가 묻는 질문이 아니라고 생각합니다. 어쩌면 나는 질문을 얻지 못할 수도있다. IMHO, 첫 번째 섹션은 질문, 사적 생성자 및 그걸 –

+0

@JuanMendes라고 부르는 팩토리 메서드에 완전히 대답합니다. OP가 잘못된 이유로이 질문을 한 것으로 의심되기 때문에 가능한 한 많은 세부 정보를 제공하고 싶었습니다. 또한 "이 재정의 가능한 init() 접근 방식에 대한 다른 접근 방식도 환영합니다"라고 대답합니다. – plalx

+0

당신은 상속을위한 생성자에서 초기화 로직을 피할 필요가 있었기 때문에 init 함수의 이유가 맞습니다. 그러나 Object.create를 사용하여 프로토 타입 체인을 대신 설정할 수 있으므로 논리를 생성자로 다시 이동할 수 있습니다. 고맙습니다! –

관련 문제