Skip to content

Commit

Permalink
Update Object.prototype.spawn example to use Object.defineProperty no…
Browse files Browse the repository at this point in the history
…w that node supports it.
  • Loading branch information
creationix committed Apr 15, 2010
1 parent 1f54f03 commit 4008ca9
Show file tree
Hide file tree
Showing 2 changed files with 3 additions and 5 deletions.
4 changes: 2 additions & 2 deletions articles/prototypal-inheritance/spawn.js
Expand Up @@ -36,15 +36,15 @@ 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)) {
defs[key] = {value: props[key], enumerable: true};
}
}
return Object.create(this, defs);
}
}});

//animals2
var Animal = {
Expand Down
4 changes: 1 addition & 3 deletions articles/prototypical-inheritance.markdown
Expand Up @@ -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.

<prototypal-inheritance/spawn.js#proto-spawn*>

Which is used as:

<prototypal-inheritance/spawn.js#animals2*>

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.
Expand Down

0 comments on commit 4008ca9

Please sign in to comment.