2017-04-24 1 views
0

각도를 사용하여 공장에서 자기 참조 패턴을 설정하는 올바른 방법은 무엇입니까?각도 팩토리 자체 참조

angular.module('app.factories') 

.factory('PersonFactory', function(PersonFactory) { 

    function Person(name) { 
    this.name = name; 

    this.mom = new PersonFactory('Frank'); 
    this.dad = new PersonFactory('Sue'); 
    } 

    Person.prototype.getMom = function() { 
    return this.mom; 
    }; 

    Person.prototype.getDad = function() { 
    return this.dad; 
    }; 

    return Person; 
}); 

이 (명백하게) 순환 종속성 에러를 반환한다 : 예를 들어, I는 동일한 유형의 객체에 부모 - 자식 관계를 갖는다.

+0

gah, 나는 그것이 단순하다는 것을 알았습니다. 대신 그것을 주입하고 공장을 사용하려고 직접 개체를 사용해야합니다 : \ 감사합니다! 응답으로 제출하여 승인 된 답변으로 표시 할 수 있습니다. :) – ossys

답변

3

생성자에서 자신을 만드는 개체를 만들 수 없습니다. 그렇지 않으면 무한 루프가 발생합니다. 개체는 생성자 매개 변수로 부모를 가져 오거나 세터를 추가해야합니다.

function Person(name, father, mother) { 
    this.name = name; 
    this.father = father; 
    this.mother = mother; 
} 

var child = new Person("Timmy", new Person("Frank"), new Person("Sue"); 

직접 공장 선언 내부 Person를 사용할 수 있습니다. 주입 할 필요가 없습니다.

function Person(name, parent) { 
    this.name = name; 
    if(!parent) { 
     this.mom = new Person("Sue", true); 
    } 
} 

var child = new Person("Timmy");