Javascript中的继承-原型不在定义部分?

Javascript中的继承-原型不在定义部分?,javascript,class,inheritance,prototype,Javascript,Class,Inheritance,Prototype,我目前正在从AS3切换到JavaScript。 我在理解继承概念方面仍然有一些困难。 我不明白的是为什么以下代码不能正常工作: Base = function () { this.coolVar = "great"; } SmallControl = function () { // Inheritance: this.prototype = new Base(); this.prototype.constructor = SmallControl;

我目前正在从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
只是构造函数的一个有意义的属性。对象的实际原型(在某些环境中可作为属性
\uuuuu proto\uuuuu
访问,但不可移植)在构建对象时设置为构造函数的
prototype
属性。对构造函数原型的更改(向原型添加属性)将反映在活动对象中,但如果将
constructor.prototype
设置为完全不同的对象,则不会反映


在构造函数中,您正在设置构造对象的
prototype
属性(
this
)。这个属性对于不是构造函数的东西没有特殊意义。当您在函数外部设置它时,您就在构造函数上设置了它。

--David--很好的经典继承示例!罗曼,这会有用的。然而,如果您需要更高的效率,您将需要研究“构造函数窃取”。然后您需要替换SmallControl.prototype=new Base();因为您将调用super的构造函数两次。然后需要实现一个helper方法来继承cproto(Sub,Sup)。我所有的代码都在工作,TDD都在这里:在我看来,当您定义:this.prototype.init时,您在prototype对象上定义了init,而不是SmallControl对象,因为“this”与SmallControl不同——它是SmallControl运行时实例化的“current object”。这就是foo.prototype.init可以工作的原因。当你说“把原型定义放在外面…”时,我想你是这样做的:SmallControl.prototype=function init(aMap)-是的,这会起作用,这是执行经典继承时的惯用用法。示例: