2016-06-01 7 views
-1

JavaScript에서 추상 팩토리 메소드를 사용하는 방법은 무엇입니까? 자바의 예를 들면 다음과 같습니다JavaScript로 추상 팩토리 메소드를 구현하는 방법은 무엇입니까?

public abstract class SuperClass { 
    abstract String bar(); 

    public String foo() { 
     return bar(); 
    } 
} 

public class SubClass extends SuperClass{ 
    @Override 
    String bar() { 
     return "bar"; 
    } 
} 

public class Test { 
    public static void main(String[] args) { 
     System.out.println(new SubClass().foo()); 
    } 
} 

bar과 잘 보여줍니다. 하지만 자바 스크립트에서 이것을 시도한 경우 :

var SuperClass = function() {}; 
SuperClass.prototype.foo = function() { 
    return this.prototype.bar(); 
}; 

var SubClass = function() {}; 
SubClass.prototype = Object.create(SuperClass.prototype); 
SubClass.prototype.constructor = SubClass; 

SubClass.prototype.bar = function() { 
    return "bar"; 
}; 

var myClass = new SubClass(); 
console.log(myClass.foo()); 

나는 Uncaught TypeError: Cannot read property 'bar' of undefined이됩니다. 내가 버그를 추적하고 SuperClass.prototype.foo이 실행될 때 SubClass.prototype은 여전히 ​​undefined입니다.

그래서 올바른 방법은 무엇입니까? 감사합니다!

답변

1

__proto__ 필드를 통해 객체의 프로토 타입에 액세스 할 수 있습니다. 그래서 변경할 경우 :

SuperClass.prototype.foo = function() { 
    return this.prototype.bar(); 
}; 

로 :

SuperClass.prototype.foo = function() { 
    return this.__proto__.bar(); 

}; 

귀하의 예제가 작동합니다. 당신은 return this.bar()를 호출 할 수 있으며 방법은 프로토 타입 체인에 발견 될 때까지 프로토 타입 통과, 자바 스크립트에 의해 자동으로 실행됩니다,

return Object.getPrototypeOf(this).bar(); 
return this.constructor.prototype.bar(); 

을하지만 : 당신은 또한 사용할 수 있습니다.

+0

나는 바보 같은 질문이지만 여전히 답변 해 주신 것을 알고 있습니다. – user3928256

+1

그리고 더 중요하게,'this.bar()'를 사용함으로써'bar()'의 범위는 prototype-object가 아닌 현재의 인스턴스로 설정 될 것입니다. 'this'의 속성에 액세스 할 때 중요 할 수 있으며 수정할 때 더욱 중요 할 수 있습니다. – Thomas

+0

@ 토마스, 잘 말했다! 나는 그것을 언급하는 것을 잊었다. – Dimos

1

프로토 타입에 bar에 액세스하면 안됩니다. 인스턴스에 액세스하면됩니다.

return this.bar();