There's no measurable drawback, like a performance hit. At least nobody mentioned any. So this is a question of personal preference and experiences.
The main pro argument: It looks better and is more intuitive: syntax sugar. It is a type/instance specific function, so it should be specifically bound to that type/instance.
The main contra argument: Code can interfere. If lib A adds a function, it could overwrite lib B's function. This can break code very easily.
Both have a point. When you rely on two libraries that directly change your types, you will most likely end up with broken code as the expected functionality is probably not the same. I totally agree on that. Macro-libraries must not manipulate the native types. Otherwise you as a developer won't ever know what is really going on behind the scenes.
And that is the reason I dislike libs like jQuery, underscore, etc. Don't get me wrong; they are absolutely well-programmed and they work like a charm, but they are big. You use only 10% of them, and understand about 1%.
That's why I prefer an atomistic approach, where you only require what you really need. This way, you always know what happens. The micro-libraries only do what you want them to do, so they won't interfere. In the context of having the end user knowing which features are added, extending native types can be considered safe.
TL;DR When in doubt, don't extend native types. Only extend a native type if you're 100% sure, that the end user will know about and want that behavior. In no case manipulate a native type's existing functions, as it would break the existing interface.
If you decide to extend the type, use Object.defineProperty(obj, prop, desc)
; if you can't, use the type's prototype
.
I originally came up with this question because I wanted Error
s to be sendable via JSON. So, I needed a way to stringify them. error.stringify()
felt way better than errorlib.stringify(error)
; as the second construct suggests, I'm operating on errorlib
and not on error
itself.
0
Created by buschtoens on 2020-03-07 16:10:27 +0000 UTC
Share