James P. Wright
James P. Wright

Reputation: 9131

Javascript, simple extension method that allows multiple versions of extending object

I have a straightforward "extend" method set up like this:

extend: function(source) {
    for (var k in source) {
        if (source.hasOwnProperty(k)) {
            myThing[k] = source[k];
        }
    }
    return myThing;
}

You use it like

myThing.extend({ 
    newObj: { 
        myFunc: function () { console.log('things'); }
    }
});

and it works great.
However, I would love to add the ability to have some other piece of code call this LATER:

myThing.extend({ 
        newObj: { 
            mySecondFunc: function () { console.log('things'); }
        }
    });

and I should be able to call both myThing.newObj.myFunc() AND myThing.newObj.mySecondFunc().

I tried changing it to this:

for (var k in source) {
            if (source.hasOwnProperty(k)) {
                if (mtUtils.hasOwnProperty(k)) {
                    for (var t in k) {
                        mtUtils[k][t] = source[k][t];
                    }
                } else {
                    mtUtils[k] = source[k];
                }
            }
        }

but that doesn't seem to work.

Upvotes: 1

Views: 572

Answers (2)

Esailija
Esailija

Reputation: 140230

function extend(dest, source) {
    for (var k in source) {
        if (source.hasOwnProperty(k)) {
            var value = source[k];
            if (dest.hasOwnProperty(k) && typeof dest[k] === "object" && typeof value === "object") {
                extend(dest[k], value);
            } else {
                dest[k] = value;
            }
        }
    }
    return dest;
}
var myThing = {};
extend(myThing, {
    newObj: {
        myFunc: function() {
            console.log('things');
        }
    }
});
extend(myThing, {
    newObj: {
        mySecondFunc: function() {
            console.log('things');
        }
    }
});

myThing;
/*
Object
   newObj: Object
      myFunc: function () { console.log('things'); }
      mySecondFunc: function () { console.log('things'); }
      __proto__: Object
   __proto__: Object
*/

Upvotes: 2

xiaoyi
xiaoyi

Reputation: 6741

This should fix your problem, but why not implement a recursive version of extend?

    for (var k in source) {
        if (source.hasOwnProperty(k)) {
            if (mtUtils.hasOwnProperty(k)) {
                for (var t in source[k]) {
                    mtUtils[k][t] = source[k][t];
                }
            } else {
                mtUtils[k] = source[k];
            }
        }
    }

Upvotes: 1

Related Questions