Reputation: 5442
I'm trying to inherit the methods of one object into another.
I've got the base object , which is implemented using the Revealing Module Pattern.
Page = function(url) {
...
return { something: something_I_defined_above }
...
}
The other object where Page should inherit from is defined as a singleton. In the actual file Page is defined before Link is.
Link = function() {
this.add = function() {}
var instance = this;
Link = function() { return instance; }
}
Next I want Page to inherit from Link.
Page.prototype = new Link();
When testing this code I get undefined for the p function:
var p = new Page();
// The following line return undefined.
p.add;
Upvotes: 0
Views: 589
Reputation: 817030
You never really instantiate a Page
object. All you do is returning a plain object literal when you call
Page = function(url) {
...
return { something: something_I_defined_above }
...
}
var p = new Page();
This literal does not inherit from Page.prototype
. There are some ways to solve this, mostly depending on how you want to structure your application.
For example, instead of letting Page
inherit from Link
(does this even make sense?) you can return an object that inherits from Link
:
Page = function(url) {
...
var Constr = function(){};
Constr.prototype = new Link();
var instance = new Constr();
instance.something = something_I_defined_above;
return instance;
...
}
var p = new Page();
I'm actually unsure what would be the best approach here. It really depends on what you want. My suggestion would to not make it too complicated.
Upvotes: 3