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
입니다.
그래서 올바른 방법은 무엇입니까? 감사합니다!
나는 바보 같은 질문이지만 여전히 답변 해 주신 것을 알고 있습니다. – user3928256
그리고 더 중요하게,'this.bar()'를 사용함으로써'bar()'의 범위는 prototype-object가 아닌 현재의 인스턴스로 설정 될 것입니다. 'this'의 속성에 액세스 할 때 중요 할 수 있으며 수정할 때 더욱 중요 할 수 있습니다. – Thomas
@ 토마스, 잘 말했다! 나는 그것을 언급하는 것을 잊었다. – Dimos