Fork me on GitHub

Extending JS Prototypes in Non-Invasive Way

This post has been updated at 16/05/2013.

The most serious reason for not extending prototypes of things like Object or Array is that you'll break iterations. For example

The most serious reason for not extending prototypes of things like Object or Array is that you'll break iterations. For example

var sys = require("sys");

// let's write the extend function
var extend = function extend (another) {
  var properties = Object.keys(another);
  var object = this;
  properties.forEach(function (property) {
    object[property] = another[property];
  });
  return object;
};

// add it to the Object.prototype
Object.prototype.extend = extend;

// objects initialization
var object  = {name: "Jakub"};
var another = {surname: "Stastny"};

// and let's check iterate over its properties
for (property in object) {
  sys.puts(property)
};

// output
// => name
// => surname
// => extend

Very annoying. Fortunately JavaScript 1.9.3 introduced function Object.defineProperty which gives us higher control and mainly can hide the property for iterators.

Object.defineProperty(Object.prototype, "extend", {value: extend });

for (property in object) {
  sys.puts(property)
};

// output
// => name
// => surname

And that's it! Obviously you can't use it in browsers so far, but it works in Node.js so now, I can't see any serious reason why not to extend Object.prototype when it makes sense. But obviously it has to be done really carefully.

Oh and BTW there is also Object.defineProperties when you need to define more properties at once.

PS: the extend function could use prototype inheritance like this:

var extend = function extend (another) {
  var prototype = this.__proto__;
  this.__proto__ = another;
  another.__proto__ = prototype;
  return this;
};

It's certainly better for object.extend(mixin), but if you want to merge two objects, it's better just to copy these properties.

blog comments powered by Disqus
About

RSS

All Posts IT JavaScript Node.js prototype inheritance

Tags

GitHub projects

Twitter @botanicus

Recent Comments