Abishek
Abishek

Reputation: 51

Javascript closures and Inheritance

I have two files: BaseClass.js and DerivedClass.js. Contents as below

//---------------------BaseClass.js----------------------------

(function () {
    BaseClass= function() { };
    BaseClass.prototype.getTestVar = function() {
    return 'base test variable';
    };
})();


//----------------DerivedClass.js----------------------------

(function () {
    DerivedClass= function() { };
    DerivedClass.inherits(BaseClass);
    DerivedClass.prototype = new BaseClass();
    DerivedClass.prototype = {
        newvar : 'derived func variable ',
        getNewVar : function() { return this.newvar; }
    };
})();

In my html file 'test.html' I have the following

var dc = new DerivedClass();
alert(
    'The value in newvar of derived class ' + dc.getNewVar() + 
    ' base class variable ' + dc.getTestVar()
);

I get the Javascript error that dc.getTestVar() is not a function. Any help in solving this is highly appreciated.

Upvotes: 1

Views: 162

Answers (2)

Matchu
Matchu

Reputation: 85802

Check out these few lines:

DerivedClass.prototype = new BaseClass();
DerivedClass.prototype = {
    newvar : 'derived func variable ',
    getNewVar : function() { return this.newvar; }
};

First it assigns a new BaseClass as the prototype, but then the next line overwrites that prototype with a fresh object. Perhaps you need to assign DerivedClass.prototype.newvar and DerivedClass.prototype.getNewVar separately — assuming that falls in line with whatever classical inheritance library you're using that provides the inherits method.

That is,

DerivedClass.prototype = new BaseClass();
DerivedClass.prototype.newvar = 'derived func variable';
DerivedClass.prototype.getNewVar = function() { return this.newvar; }

Still, this seems like a mix of classical and prototypal inheritance. Consider reading up on the documentation of that classical inheritance library and see if there's a more consistent way of doing this sort of thing.

For example, if you're using Crockford's classical inheritance (a guess from the inherits keyword), this seems to be his intended way to declare a method:

DerivedClass.method('getNewVar', function () { return this.newvar });

Granted, that's exactly equivalent to what you're already doing, but, if we're gonna use his library, may as well use his style for consistency.

Upvotes: 2

Hubro
Hubro

Reputation: 59333

At this point:

DerivedClass.prototype = new BaseClass();
DerivedClass.prototype = {
    newvar : 'derived func variable ',
    getNewVar : function() { return this.newvar; }
};

You're first setting the prototype to the BaseClass, but then overwriting it with a new object. Try this instead:

DerivedClass.prototype = new BaseClass();
DerivedClass.prototype.newvar = 'derived func variable ';
DerivedClass.prototype.getNewVar = function() { return this.newvar; };

Upvotes: 2

Related Questions