On Oct 18, 3:08 pm, buda <www...@pochta.ru> wrote:
> T.J. what the reasons not to make them Object.prtototype methods?

If you add something to `Object.prototype`, it shows up on *every*
object. So for instance:

Object.prototype.foo = function() {
    return "bar";
var a = {};
console.log(typeof a.foo);
// -> "function"
for (var name in a) {
// -> "foo"

To put it mildly, this causes a problem because people expect a blank
object to be, um, blank. And in fact, you see people repeatedly
running into problems with Prototype's additions to `Array.prototype`
because they're using `for..in` incorrectly[1][2]. Compare the output
of this page:
with this one:

The code is identical in the two pages, it's just that the second one
includes Prototype and the first one doesn't. Since Prototype adds a
bunch of `Array.prototype` properties, they show up on that naive
(broken) `for..in` loop.

As of ECMAScript5 it's possible to put properties on
`Object.prototype` (and `Array.prototype`) that *won't* break naive
`for..in` loops by using `Object.defineProperty` and setting
`enumerable` to `false`, but there's still the problem that people
expect a blank object to be blank. And so if (for instance) you put a
`keys` property on `Object.prototype` that refers to a function that
returns the object's keys, but I have code where I use a `keys`
property on an object to mean something else entirely (very likely,
and in fact I *have* done it), there's a problem. For that reason, the
list of properties defined for `Object.prototype` in the spec[3] is
very short and likely to stay that way, in favor of properties defined
on `Object` that you pass an instance into (like `Object.keys`).

[1] http://blog.niftysnippets.org/2010/11/myths-and-realities-of-forin.html
[2] http://api.prototypejs.org/language/Array/
[3] http://es5.github.com/#x15.2.4

T.J. Crowder
Independent Software Engineer
tj / crowder software / com
www / crowder software / com

You received this message because you are subscribed to the Google Groups 
"Prototype & script.aculo.us" group.
To post to this group, send email to prototype-scriptaculous@googlegroups.com.
To unsubscribe from this group, send email to 
For more options, visit this group at 

Reply via email to