views:

153

answers:

2

Hi

I am currently switching from AS3 to Javascript.
I still have some trouble with understanding inharitance-concepts.
What I do not understand is why the following code is not working properly:

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

If I put the prototype definitions outside of the "SmallControl"-Function everything wokrs fine... but I don't understand that.

Thanks in advance!

+1  A: 

I think you want something like this:

// 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();
David Dorward
-- David -- nice classical inheritance example! Roman, this WILL work. However, if you need more efficiency you will want to research: "Constructor Stealing". Then you will want to replace the SmallControl.prototype = new Base(); line because you will be calling the super's constructor twice. You'll then need to implement a helper method to inheritcProto(Sub, Sup). I have all of this code working and TDD'd here: http://github.com/roblevintennis/Testing-and-Debugging-JavaScript
Rob
+1  A: 

prototype is only a meaningful property of constructors. The object's actual prototype (which is accessible in some environments as the property __proto__, but this is not portable) is set to be the constructor's prototype attribute at the time the object is constructed. Changes to the constructor's prototype (adding properties to the prototype) will be reflected in live objects, but not if you set Constructor.prototype to be a completely different object.

In your constructor, you're setting the prototype attribute of the constructed object (this). This attribute has no special meaning on something that's not a constructor function. When you set it outside of the function, you set it on the constructor function.

Miles