Object constructor function got several methods during the past updates of js like apply, assign, entries, fromEntries, keys, values...
These would be excellent candidates to be included in object prototype.
Object.prototype.values = function(f) {
return Object.values(this)
}
We could even combine them to implement map or filter:
Object.prototype.map = function(f) {
return Object.fromEntries(Object.entries(this).map(f))
}
// now we could do...
obj1 = {a:1, b:2}
obj1.values() // [1,2]
obj1.map([a,b] => ['x'+a: b+1]) // {xa:2, xb:3}
This syntax would have been unquestionably superior compared to eg.
Object.fromEntries(Object.entries(obj1).map([a,b] => ['x'+a: b+1])))
But even
obj1.entries()
.map([a,b]=>['x'+a: b+1])
.fromEntries()
is much more readable.
Backward compatibility doesn't seem to be a problem, since further objects in the prototype chain would mask the methods (eg. Array.prototype.map would still work properly).
Other route was taken, and there must be a technical reason. I'm pretty much curious what it is.
Are there any examples (possibly in legacy code) where the above approach would fail?
Having too many extra properties on all objects is problematic because it would be difficult or confusing to use those names as regular keys on objects.
For instance, values is a valid key name on an object, e.g. {values: [1,2,3]}. In the example in the question, if this property could be modified, then calling .values() on an object would not always work. If this property is non-configurable, then it would be impossible to use values as a regular key name, which is undesirable.
Adding to what Unmititgated already stated, adding these methods to the prototype would make them unavailable on objects created from null, which shouldn't be the case on newly introduced object methods.
Object.prototype.values = function() {
return Object.values(this)
}
let obj = Object.create(null);
obj.name = "Peter";
obj.age = 34;
console.log(Object.values(obj)); // works
console.log(obj.values()); // error
The proposal for Object.hasOwn explicitly mentions this aspect.