Reputation: 23
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.
Upvotes: 1
Views: 212
Reputation: 169383
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.
Upvotes: 0
Reputation: 7715
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)?
Upvotes: 1