dcsimg
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

By submitting your information, you agree that devx.com may send you DevX offers via email, phone and text message, as well as email offers about other products and services that DevX believes may be of interest to you. DevX will process your information in accordance with the Quinstreet Privacy Policy.


advertisement
 

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


advertisement

WEBINAR:

On-Demand

Building the Right Environment to Support AI, Machine Learning and Deep Learning


Building JavaScript Objects
Suppose you wanted to create an object in JavaScript modeled after a person. This person object will contain two properties (for now)—a last name and a first name. First, design the prototype function:

function person() { }

Next, add the parameters used to initialize the properties:

function person(first,last){ }

Finally, assign the parameters to property placeholders within the prototype:



function person(first,last) { this.firstName = first; this.lastName = last; }

Notice that the properties, firstName and lastName, are nested within the prototype. The this keyword seems to associate them with the object but, as you'll see a little later, the this keyword also makes the properties publicly available to outside routines. In fact, the nesting of the properties alone makes them local to the object.

Later in your code, you can create as many person objects as you'd like, each of which automatically has firstName and lastName properties:

var tDuffy = new person("Tom","Duffy");

So, if JavaScript does indeed use inheritance, does it also make use of other object-oriented principles? The answer is—although it's under-used, yes; JavaScript also handles encapsulation.


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