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;
1 Answer 1
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.
7 Comments
new, so it will return this at the first call and instance on any subsequent call (with or without new).new, this will refer to a new object that inherits from the functions prototype. If no object is explicitly returned by the function, this is returned implicitly. You can try to return a number or string and you will see that you get this nonetheless.Explore related questions
See similar questions with these tags.