views:

194

answers:

1

Hi,

I have a question about some sample code shown on page 55 of this book

var coolcat = function (spec) {
    var that = cat(spec),
        super_get_name = that.superior('get_name');

        // Can I replace the line above with the line below?
        // super_get_name = that.get_name();

    that.get_name = function (n) {
        return 'like ' + super_get_name() + ' baby';

        // And the line above with the line below?
        // return 'like ' + super_get_name + ' baby';
    };
    return that;
};

Can anybody tell me whether the replacement suggested in the comments would achieve the same result? If so, then the 'superior' method proposed in this section of the book seems pointless.

Thanks, Don

+1  A: 

In the above case, yes it will produce the same result and won't make any difference because you are invoking the function directly instead of returning it and then invoking...and also note that you are only invoking the function only once...which brings me to the next point:

I still think the Object.superior helper method is useful because since it returns a reference to the function itself, the returned function from the superclass will be stored in the variable and accessible even if the property is modified later on.

As you can see from the above example, after you are invoking the function (that.get_name(); <= from your commented section), you are overwriting it with the subclass's new function:

that.get_name = function (n) {
        return 'like ' + super_get_name() + ' baby';
}

Thus you couldn't later on call the superclass's method since you have just overridden it.

But, if you use the superior method, you will store that function in a variable, and you will have access to it even after you override the (get_name) method.

Andreas Grech
Sorry, my suggested replacement was incomplete - I've fixed it now
Don
which renders my explanation useless now :P
Andreas Grech
Yes, sorry about that. If you think my suggested replacement would now achieve the same result, feel free to edit your response to say "Yes" or "No, because...."
Don
Well in that case, there is no need for the superior method in the above case since you're invoking the function directly. But I'm trying to think of an otherwise suitable use for the 'superior'method
Andreas Grech
Posted updated answer now, and removed the old one.
Andreas Grech