Search code examples
javascriptextend

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.


Solution

  • 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];
                }
            }
        }