JavaScript의 상속 - 정의 부위가 아닌 protoyping?
-
05-07-2019 - |
문제
현재 AS3에서 JavaScript로 전환 중입니다.
나는 여전히 상속-개념을 이해하는 데 어려움을 겪고 있습니다.
내가 이해하지 못하는 것은 다음 코드가 제대로 작동하지 않는 이유입니다.
Base = function () {
this.coolVar = "great";
}
SmallControl = function () {
// Inheritance:
this.prototype = new Base();
this.prototype.constructor = SmallControl;
this.prototype.init = function(aMap) {
console.log('init');
console.log('coolVar?: ' + this.coolVar);
}
}
var foo = new SmallControl();
//foo.init(); // --> TypeError: foo.init is not a function
foo.prototype.init(); // --> works
프로토 타입 정의를 "smallcontrol"-기능 외부에 넣으면 모든 것이 잘 작동하지만 이해가 안 돼요.
해결책
나는 당신이 다음과 같은 것을 원한다고 생각합니다.
// Create the super class
Base = function () {
this.coolVar = "great";
};
// Create the new class
SmallControl = function () {
};
// Set the prototype of SmallControl to be an instance of Base.
// This runs the Base constructor _immediately_ which sets up the variable
SmallControl.prototype = new Base();
// Add the init method to the SmallControl class
SmallControl.prototype.init = function(aMap) {
console.log('init');
console.log('coolVar?: ' + this.coolVar);
}
// Create an instance of SmallControl
var foo = new SmallControl();
foo.init();
다른 팁
prototype
생성자의 의미있는 속성 일뿐입니다. 물체의 실제 프로토 타입 (일부 환경에서는 속성으로 액세스 할 수 있습니다. __proto__
, 그러나 이것은 휴대용이 아닙니다) 생성자의 것으로 설정되었습니다. prototype
객체가 구성 될 때 속성. 생성자의 프로토 타입 변경 (프로토 타입에 특성 추가)이 라이브 객체에 반영되지만 설정하는 경우에는 그렇지 않습니다. Constructor.prototype
완전히 다른 대상이되기 위해.
당신의 생성자에서 당신은 설정합니다 prototype
기인하다 구성된 물체의 (this
). 이 속성은 생성자 함수가 아닌 것에 특별한 의미가 없습니다. 함수 외부에서 설정하면 생성자 함수로 설정합니다.
제휴하지 않습니다 StackOverflow