Better world by better software

submited by
Style Pass
2021-11-25 20:30:07

Of course these design decisions in EcmaScript 5 are not accidental. Prototypical JavaScript inheritance relies on having a prototype for every object. Most object design patterns rely on being able to distinguish own property vs inherited, etc. But it also leads to weird things like these (giving JavaScript a bad name):

The really surprising 16 in the last example comes from JavaScript picking to use valueOf() when an object is used in an arithmetic expression. {}.valueOf returns the object itself via Object.prototype.valueOf. So it is back to square one: adding object to number 1. So VM tries second approach: using toString. {}.toString() is a string "[object Object]" returned by Object.prototype.toString. Then 1 is concatenated to the result because when adding to a string, anything else is typecast as a string too. The final step is "[object Object]1".length which returns 16 characters.

There is a way to construct purely data storage key/value pairs by specifically setting new object's prototype to be undefined

Leave a Comment