【发布时间】:2009-07-30 09:08:24
【问题描述】:
我目前正在从 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”-Function 之外,一切正常……但我不明白。
【问题讨论】:
-
乍一看,在我看来,当您定义时: this.prototype.init 您在原型对象而不是 SmallControl 对象上定义了 init,因为“this”与 SmallControl 不同 - 它是在运行时实例化 SmallControl 时的“当前对象”。这就是 foo.prototype.init 起作用的原因。当你说“将原型定义放在外面......”时,我假设你做了: SmallControl.prototype = function init(aMap) - 是的,这将起作用,并且是进行经典继承时的习语。示例:github.com/roblevintennis/Testing-and-Debugging-JavaScript/tree/…
标签: javascript class inheritance prototype