goog.inherits with goog.base: I'm doing it wrong

285 views
Skip to first unread message

Simon Haines

unread,
Oct 25, 2010, 3:13:34 AM10/25/10
to Closure Library Discuss
I must be missing something, but from the documentation and code it
appears that if one class descends from another by using
goog.inherits, it can then call into the superclass (including its
constructor) by using goog.base.

However, considering the following code:

superclass = function(property1, property2) {
this.property1 = property1;
this.property2 = property2;
};

superclass.prototype = {
getProperty1: function() {
return this.property1;
},
getProperty2: function() {
return this.property2;
}
};

subclass = function() {
goog.base(this, "one", "two");
};

goog.inherits(subclass, superclass);

s = new subclass();
document.write(s.getProperty1());
document.write(s.getProperty2());


The result is "UndefinedUndefined", i.e. the superclass constructor is
never called, even though the prototype chain is in place (which is
why the getProperty methods can be called from the subclass).

Everything appears OK when stepping through. Obviously I'm doing it
wrong, but in what way?
Many thanks.

Daniel Steigerwald

unread,
Oct 25, 2010, 4:31:25 AM10/25/10
to Closure Library Discuss
Hi, you are overriding constructor by
prototype = {}.. Look

var Superclass = function (property1, property2) {
this.property1 = property1;
this.property2 = property2;
};

// this overrides constructor Superclass.prototype = {};

// this is how Google Closure methods should be defined
Superclass.prototype.getProperty1 = function () {
return this.property1;
};
Superclass.prototype.getProperty2 = function () {
return this.property2;
};

var Subclass = function () {
goog.base(this, "one", "two");
};
goog.inherits(Subclass, Superclass);

// this would fix it, but better to be unfixed
// Superclass.prototype.constructor = Superclass;

var s = new Subclass();
alert(s.getProperty1());

All methods should be defined directly on prototype object
prototype.methodA = fn..

(inherits method can be fixed, but better is not to allow override
prototype, because subclasses must mix methods anyway)

Simon Haines

unread,
Oct 25, 2010, 8:25:47 PM10/25/10
to Closure Library Discuss
Ah of course, the prototype.constructor property gets clobbered.
Thanks for clearing this up.
Reply all
Reply to author
Forward
0 new messages