{about: ["software","computing","maths","business","etc"]}



Extending Objects in Node.js

So you’ve been playing with Node.js and now you are at this point where you want to take your well acquired jQuery plugin development knowledge to Node.js but realise that there’s no such thing as $.extend() to combine your userland and API options in Node.


You could simply create Object.prototype.extend and create a new function, but this presents a fundamental flaw: A for/in loop iterates over all the properties of an object. By only defining Object.prototype.extend we create a new property for the loops to iterate over. This can cause quite some pain. If you would like to know more, I’d suggest this bedtime reading. The article contains a good description of why Object.prototype is bad compared to Object.defineProperty.

Back to original issue

What we wanted was quite simple, the ability to extend. If we’re in our Node.js module, we want to be able to grab the properties of an object, and merge/overwrite with the other properties of the second object.


This is how you do it:

Object.defineProperty(Object.prototype, "extend", {
    enumerable: false,
    value: function(from) {
        var props = Object.getOwnPropertyNames(from);
        var dest = this;
        props.forEach(function(name) {
            if (name in dest) {
                var destination = Object.getOwnPropertyDescriptor(from, name);
                Object.defineProperty(dest, name, destination);
            }
        });
        return this;
    }
});

Now you can easily do something like:

var default = {
    timeout: false,
    name: 'example',
};

var opts = {
    name: 'blogpost'
};

default.extend(opts);

As you can see, it is quite similar to how one would do it with jQuery using $.extend(default, opts); 


And the resulting object will be:

{
    timeout: false,
    name: 'blogpost',
};

Hopefully this helps and puts you on the path to righteousness :-)

"when": " 2010-11-09T20:38:00+00:00, "by": "davidcoallier"
permalink
tagged: javascript, jquery, nodejs, developers,


Notes
  1. davidcoallier posted this




blog comments powered by Disqus