javascript - Javascript 中的继承 - 原型(prototype)不在定义部分?

标签 javascript class inheritance prototype

我目前正在从 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/

相关文章:

java - 在 Java 的同一个接口(interface)中实现多个类?

javascript - 如何在调用下一个 Javascript 函数之前更新浏览器?

c++ - 未定义对 C++ 中析构函数错误的引用?

java - 在创建扩展父 fragment 的子 fragment 时调用 newInstance()

c++ - 扩展现有的 C++ 类

c++ - 如何将方法结果作为参数传递给 C++ 中的基类构造函数?

javascript - 将 HREF 替换为标签之间的内容(使用电子邮件表达式)

javascript - 如何从 Javascript 中的 AtomPub XML HTTP 响应中提取值(适用于 Google Apps 管理设置 API)

javascript - 从 HTML 标记中为 observable 赋予初始值

c++ - 派生类中不可用的赋值运算符