During a conversation with another developer, the topic of hacking into JavaScript private functions arose and whether it is a viable option.
Two alternatives were discussed:
- Using a constructor and prototype containing all functions, where non-API methods (private) are identified by an underscore
_function_name
for clarity on what can and cannot be called. - Creating a constructor and prototype for API functions, with free functions as private functions within a private namespace to isolate them from other namespaces.
Other approaches were dismissed, such as creating private functions in the constructor using var private_var = function(){}
due to each object instantiation generating its own set of functions.
The reasoning behind these options included:
1
- Javascript lacks support for true private functions, making this approach essentially a workaround
- Using underscores in method names helps define boundaries within classes/prototypes, similar to Python's lack of private methods without causing concern among users
- Enforcing private methods may not make sense in a language where public methods can be dynamically substituted
- This method impacts readability as private functions require separate scope braces, do not have access to
this
, and need to be invoked withfunction.call(object)
orfunction.apply(object)
2
- Encapsulating private methods away from class/prototype users provides a clear limitation
- This approach aligns with industry standards, widely adopted by many Javascript developers
The suspicion arises that besides common usage, there might be additional reasons like performance driving the adoption of this approach.
Due to limited knowledge of Javascript, the decision was made to seek input on StackOverflow regarding the ideal approach and reasons behind it.