From 4008ca942f216b3d7f19a53eed5a8d7d8a53c670 Mon Sep 17 00:00:00 2001 From: Tim Caswell Date: Wed, 14 Apr 2010 22:37:33 -0500 Subject: [PATCH] Update Object.prototype.spawn example to use Object.defineProperty now that node supports it. --- articles/prototypal-inheritance/spawn.js | 4 ++-- articles/prototypical-inheritance.markdown | 4 +--- 2 files changed, 3 insertions(+), 5 deletions(-) diff --git a/articles/prototypal-inheritance/spawn.js b/articles/prototypal-inheritance/spawn.js index 2660d33..34c82d5 100644 --- a/articles/prototypal-inheritance/spawn.js +++ b/articles/prototypal-inheritance/spawn.js @@ -36,7 +36,7 @@ sys.puts(pete); //proto-spawn -Object.prototype.spawn = function (props) { +Object.defineProperty(Object.prototype, "spawn", {value: function (props) { var defs = {}, key; for (key in props) { if (props.hasOwnProperty(key)) { @@ -44,7 +44,7 @@ Object.prototype.spawn = function (props) { } } return Object.create(this, defs); -} +}}); //animals2 var Animal = { diff --git a/articles/prototypical-inheritance.markdown b/articles/prototypical-inheritance.markdown index 6989db2..9166365 100644 --- a/articles/prototypical-inheritance.markdown +++ b/articles/prototypical-inheritance.markdown @@ -51,7 +51,7 @@ Then you can create hierarchies of objects easily: ## Using `Object.prototype.spawn` -If you're really brave and don't mind messing with `Object.prototype`, then there is an even shorter way: +Now that node supports `Object.defineProperty`, we can add methods to `Object.prototype` that are not enumerable and thus don't break stuff. @@ -59,8 +59,6 @@ Which is used as: -Just make sure to understand that adding enumerable properties to Object.prototype breaks all `for ... in` loops that don't have a `hasOwnProperty` check in them. You've been warned. - ## Where do we go from here? I'm not sure if this is a good idea or not. You give up a lot by not having constructor functions that initialize state of objects. It could be baked into the `Object.spawn` method, but then you're dealing more with classical OOP emulations.