我目前正在从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之外,则一切正常……但是我不明白。

最佳答案

我想你想要这样的东西:

// 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();

10-08 19:42