我目前正在从 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
如果我将原型(prototype)定义放在“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();
关于javascript - Javascript 中的继承 - 原型(prototype)不在定义部分?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1205385/