Adding methods to Object / Number / String prototype
Disclaimer
This thread is supposed to serve as a help for other people encountering
similar problems as well as checking whether there are better solutions. I
will attach my own solution, but ideas and improvements (besides making it
more generic) are welcome.
I know that generally, extending the built-in objects is a bad idea. So an
assumption for this thread is that there is a good reason and no way
around it.
Scenario
As a developer, I want to add a method someMethod to all Javascript
objects, wherein the implementation is different for Object, Number and
String.
I want the solution to meet the following acceptance criteria:
A) The solution works in a browser
A1) The solution works in strict mode in case the script is used within a
strict context
A2) The solution works in non-strict mode because 'use strict'; will be
removed during compression in, e.g., the YUI Compressor[1]
B) The solution works in node.js
B1) The solution works in strict mode (reason see A1)
B2) The solution works in non-strict mode for the same reason as in B2,
plus strict mode in node.js cannot be activated on function level[2]
C) I want other objects to be allowed to override this method
D) If possible, I want to have control over whether or not the method
shows up in a for .. in loop to avoid conflicts with other libraries
E) The solution shall actually modify the prototypes.
[1] Minfication removes strict directives
[2] Any way to force strict mode in node?
No comments:
Post a Comment