JavaScript에서 클래스를 올바르게 확장하는 방법에 대해 잘 알고 있다고 생각했지만 하위 클래스를 확장 할 때 메서드를 재정의하고 자식 클래스에서 부모 메서드를 호출 할 때 무한 루프가 발생합니다. 내가 잘못하고 있거나 JavaScript에서 이런 식으로 하위 클래스를 만들면 안됩니다.
누구든지 나를 교육하도록 도울 수 있습니까?
var Grand = function() {
this.test();
};
Grand.prototype.constructor = Grand;
Grand.prototype.test = function() {
console.log( "Grand!")
};
var Parent = function() {
this.supr.constructor.call( this );
};
Parent.prototype = Object.create( Grand.prototype );
Parent.prototype.constructor = Parent;
Parent.prototype.supr = Grand.prototype;
Parent.prototype.test = function() {
this.supr.test.call( this );
console.log( "Parent!" );
};
var Child = function() {
this.supr.constructor.call( this );
};
Child.prototype = Object.create( Parent.prototype );
Child.prototype.constructor = Child;
Child.prototype.supr = Parent.prototype;
Child.prototype.test = function() {
this.supr.test.call( this );
console.log( "Child!" );
};
var g = new Grand(); // Outputs "Grand!"
var p = new Parent(); // Outputs "Grand!" "Parent!"
var c = new Child(); // Error: Endless Loop!
콘솔에 "Grand!", "Parent!", "Child!"가 기록 될 것으로 예상합니다. new Child ()를 인스턴스화 할 때 대신 무한 루프를 얻습니다.
저는 ActionScript 배경에서 왔기 때문에 JavaScript로 클래스를 만들면 여전히 커브 볼이 약간 발생합니다. 미리 도와 주셔서 감사합니다!
문제는 다음 코드에 있습니다.
var Parent = function() {
this.supr.constructor.call( this );
};
이 코드가 실행될 때 어떤 일이 발생하는지 고려하십시오.
var c = new Child();
다음 this
은 변수 c
이므로 this.supr.constructor
다음 코드 줄에서 설정시 항상 부모의 생성자가됩니다.
Child.prototype.supr = Parent.prototype; // i.e. this.supr = Parent.prototype
Parent.prototype.constructor = Parent; // i.e. this.supr.constructor = Parent
그래서, 아이의 생성자를 발동 할 때 this.supr.constructor.call( this );
그것이 실행 Parent
기능을하고, 부모 함수가 다시 실행 this.supr.constructor.call( this );
결과 Parent
함수가 무한 루프가 발생, 다시 호출된다.
수정 사항은 다음과 같이 기본 클래스 함수를 호출하는 것입니다.
var Child = function() {
Child.prototype.supr.constructor.call( this );
};
이 게시물의 자세한 내용
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다