현재 AS3에서 JavaScript로 전환 중입니다.
나는 여전히 상속 개념을 이해하는데 약간의 문제가있다. 다음 코드가 제대로 작동되지 않는 이유
는 내가 이해하지 못하는 것은 :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();
당신이 정의했을 때 this.prototype.init는 'this'가 SmallControl과 같지 않기 때문에 Prototype 객체가 아닌 Prototype 객체가 아닌 init 객체에 대해 init을 정의했다는 것을 알 수 있습니다. - "현재 객체"입니다. SmallControl의 런타임 인스턴스화. 그래서 foo.prototype.init가 작동합니다. "프로토 타입 정의를 바깥쪽에 넣으십시오 ..."라고 말하면 여러분은 다음과 같이 가정합니다 : SmallControl.prototype = function init (aMap) - 예, 그것은 정상적인 상속을 할 때 작동하고 숙어입니다. 예 : http://github.com/roblevintennis/Testing-and-Debugging-JavaScript/tree/master/code/objects/ – Rob