Chrome 21에서 생성자 함수의 프로토 타입을 정의하는 데 문제가 있습니다. 의사 클래스 기반 구조를 구현하려고하는 큰 프로젝트에서 작업 중입니다. '하위 클래스'속성)을 매우 느슨한 데이터 캡슐화와 함께 사용하지만 JavaScript에서 프로토 타이핑 및 상속에 비교적 익숙하며 무엇이 잘못되었는지를 파악할 수 없습니다. StackOverflow에는 다른 막연한 비슷한 스레드가 있지만이 문제를 해결하는 것은 없습니다. 여기 JavaScript 객체가 프로토 타입 체인에서 상속받지 않습니다.
내가 함께 일하고 있어요 생성자 있습니다 : 직관적function Root()
{
this._subclass = "Root";
this.subclass = function(){
return this._subclass;
};
this._date;
this.date = function(){
return this._date;
};
}
function CustomDateTime()
{
this._subclass = "CustomDateTime";
this._value = new Date();
}
CustomDateTime.prototype = new Root;
function CurrentDate()
{
this._subclass = "CurrentDate";
}
CurrentDate.prototype = new CustomDateTime;
, 내가이 작업을 수행 할 수 있어야한다고 나에게 보인다 (서브 클래스()는 Root
생성자에 정의되어 있기 때문에) :
var now = new CurrentDate();
alert(now.subclass()); // should alert "CurrentDate"
하지만 스크립트 실행시 나는 TypeError: Object #<CurrentDate> has no method 'subclass'
이됩니다. 나는이 경고를 포함하도록 CurrentDate
생성자를 변경하는 경우 또한 :
function CurrentDate()
{
alert(this._subclass);
this._subclass = "CurrentDate";
}
CurrentDate.prototype = new CustomDateTime;
결과 메시지가 undefined
입니다.
대신 var now = new CustomDateTime()
을 할당하는 경우 subclass() 메서드를 호출하면 의도 한대로 "CustomDateTime"이 반환됩니다. 또 다른 생성자 ModelObject
을 정의했으며, 프로토 타입은 Root
으로 설정되었고 subclass()는 해당 객체에서도 의도 한대로 수행됩니다.
CurrentDate 생성자가 CurrentDate : CustomDateTime : Root 체인을 빠져 나가고 있으며이 함수를 사용하여 만든 독립 실행 형 생성자 - 단순히 호출되는 것은 상속되지 않는 것입니다. CurrentDate 함수 객체에 할당 된 프로토 타입에서 가져옵니다.
JavaScript 프로토 타입을 사용하는 올바른 방법이 아닙니까? 다시 말하지만, 이것은 매우 원활하게 진행되어야한다고 생각합니다.
첫 번째 코드 예'alert (now.subclass());'가 올바르게 작동합니다. "메소드 없음"오류가 없습니다. http://jsfiddle.net/WL5tC/ –