1

Let's say I have a javascript object...

app.dooDad = {}
(function (O) {

    O.magicStuff = function() {

        alert("LOL!");

    }

    ...other methods...

})(app.doodad)

Now let's say I make a deep copy of this object...

app.specialDooDad = jQuery.extend(true, {}, app.dooDad);
(function (O) {

    O.magicStuff = function() {

        alert("LOL!");
        alert("Cats!");

    }

})(app.doodad)

I am wondering: Is there a better way to do this? That is, is there a better way to to extend the method magicStuff with additional commands in specialDooDad, without rewriting it?

thanks (in advance) for your help.

1
  • You can not extend a function in the sense of adding more commands to it. Commented Mar 7, 2011 at 19:09

2 Answers 2

1

Correct me if I'm wrong, but I believe you can do something like this in Javascript:

app.specialDooDad = jQuery.extend(true, {}, app.dooDad);
(function (O) {

    O.oldMagicStuff = O.magicStuff;

    O.magicStuff = function() {

        //Additional stuff you want to do
        alert("Cats!");
        O.oldMagicStuff();

    }

})(app.doodad)

That only works well if you are just adding on an additional thing or two, either before or after the "original" function would run. If you need to add things into the middle, I believe you just have to rewrite the function.

I'm assuming you want to do this to maintain backward compatibility with an existing codebase (such as an open source library)?

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

4 Comments

thanks for the response. Actually I am just trying to work out the best way to extend objects from general to more specialized for use in my own little app, without rewriting too much code along the way. Maybe there are better ways to do it - I am bit new to this stuff. :)
The cloning really doesn't do anything there you know.
@Raynos As I said, correct me if I'm wrong :-). How do you get it to create a new copy of the function and store it?
my way works reasonably well. Also I meant the call to jQuery.extend does nothing. Mapping the function to a variable works ok. It can be local though instead
0
function DooDad() {
    this.magicStuff = function() {
         alert("LOL!");
    }
}

app.dooDad = new ConstructorA();

function SpecialDooDad() {
    var o = new DooDad;

    this.magicStuff = function() {
         o.magicStuff.apply(this, arguments);
         alert("Cats!");
    }

}

app.specialDooDad = new SpecialDooDad;

I prefer this way of extending. It's more functional. You create new objects through composition and extension.

Comments

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.