Browse files

Update Object.prototype.spawn example to use Object.defineProperty no…

…w that node supports it.
  • Loading branch information...
creationix committed Apr 15, 2010
1 parent 1f54f03 commit 4008ca942f216b3d7f19a53eed5a8d7d8a53c670
Showing with 3 additions and 5 deletions.
  1. +2 −2 articles/prototypal-inheritance/spawn.js
  2. +1 −3 articles/prototypical-inheritance.markdown
@@ -36,15 +36,15 @@ sys.puts(pete);
-Object.prototype.spawn = function (props) {
+Object.defineProperty(Object.prototype, "spawn", {value: function (props) {
var defs = {}, key;
for (key in props) {
if (props.hasOwnProperty(key)) {
defs[key] = {value: props[key], enumerable: true};
return Object.create(this, defs);
var Animal = {
@@ -51,16 +51,14 @@ 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.
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.

0 comments on commit 4008ca9

Please sign in to comment.