The only explanation I can come up with, is that since everything inherits from Object in JS, the designers wanted to keep those Object objects as lightweight as possible.
That's it exactly. You don't want to fill up Object.prototype
with a bunch of methods, because they'd be on everything that's an object (or at least, everything that's an object that inherits from Object.prototype
, which all objects do by default though you can prevent it with Object.create
).
There's a second, more subtle reason: Because you don't want basic operations altered by objects in the general case. That's one reason you see people avoiding using the hasOwnProperty
method on an object and instead using it directly from Object.prototype
:
if (Object.prototype.hasOwnProperty.call(obj, "name")) {
// ...
}
The author of the code above wanted to avoid the possibility that hasOwnProperty
had been redefined for obj
such that it would lie. :-)
const obj = {
hasOwnProperty() {
return true;
}
};
console.log(obj.hasOwnProperty("foo")); // true
console.log(Object.prototype.hasOwnProperty.call(obj, "foo")); // false, which is correct