Site icon The Winter Blog

Javascript class methods

My understanding of javascript object methods (pre-ES6) from Douglas Crockford’s post.

Public

Can’t access private members of the object

Anything created with this.xyz inside the constructor, or

Any methods added by MyObject.prototype.myMethod outside the constructor.

Private

Not accessible from outside the object definition (e.g. as myObj.myMethod())

Any variables or functions created inside the constructor with var or function abc(){...}.

Privileged

(I.e. publicly accessible, but can access private members)1

Methods declared with this.myMethod = function()... inside the constructor.

Update

One nuance I noticed:

The private methods can access public variables but can’t modify them.
The public & privileged methods can only modify public variables.

So, a variable defined with this.publicValue = ... can be accessed directly as publicValue inside the private methods. They can’t modify this value though.

Public/privileged methods can only access these public variables using a reference, say this.publicValue, but can modify them.



  1. One downside of privileged methods is that they can be memory hogging in some circumstances. Unlike public/prototype method, they aren’t shared. So, every instance of the class creates its own copy of the privileged methods into memory. 
Exit mobile version