0

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

3

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.

Sign up to request clarification or add additional context in comments.

7 Comments

The LInk object has similar problems. First time he calls it, it returns undefined.
@Matt: Yes but it is called with new, so it will return this at the first call and instance on any subsequent call (with or without new).
I had my suspicions that the problem would be with the revealing module pattern. I can see why it doesn't work as I expected it to.
@Felix I had no idea that a 'new' call will return 'this' even in the absence of a return value. Intriguing.
@Matt: Now you know :) If you call a function with 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.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.