Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


advertisement
 

Encapsulate Your JavaScript: Keep Private Methods Private-4 : Page 4


advertisement
Encapsulation
The concept of encapsulation means that an object's data members should remain private to the object and manipulated through publicly exposed methods. In other words, programs should not have the ability to change the properties of objects directly. In traditional JavaScript, you are free to modify the values of an object's properties simply through assignment. For example, you can modify a person object's data fields directly, which breaks the concept of encapsulation:

tDuffy.firstName = "Kelli";

Encapsulation states that firstName should not be available directly for manipulation and should be manipulated through a public method:

tDuffy.setFirstName("Kelli");

Most JavaScripters find the creation of private data members (variables and methods) foreign; however, it's rather easy to implement. A typical Java class contains a constructor, private member variables, and methods, and so does a JavaScript object. You need two techniques to accomplish encapsulation in JavaScript: nested functions and omission of the this keyword in object constructors. Be aware, though, that nested functions are part of the JavaScript 1.2 release, so they won't be available in downlevel browsers.


Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date