JavaScript concept with a cup of coffee and a laptop

Membership Has Its Privileges (JavaScript)

I have written previously about private methods. It is important to understand how JS deals with private and public versus privileged objects. I plan on doing a post in the future about closures as those are a key way to handle the protection of your code, yet exposing what the program needs. In today’s post, I want to go over privileged methods.

Let’s say we have the following JS constructor…

Now, let’s say we want to get the GPA of the student. We could try this…

The above code will not work because gpa is a private variable property. We need to create a getter that is privileged. We could try this…

We are on the right track, but just adding the gradeReport method does not give us access because it is not really a getter. It simply returns what a getter would…well…get. So how do we do this? The protype code is still valid. We need to create the getter code.

Now, full disclosure…we could do this…

While that would work, most programs are a tad more complex and it would probably be wiser to create a privileged getter to grab this.grade instead of grabbing it directly in the prototyped method. The reason for this is typically, there is more logic to process inside the constructor for the retrieved property. Here is the change to the constructor…

Now we can grade the grade property and do what we want to with it outside of the constructor without messing with the internals of the constructor. Here is the complete code…

Happy Coding!

Clay Hess

Share this post

Share on facebook
Share on google
Share on twitter
Share on linkedin
Share on pinterest
Share on print
Share on email
Skip to content