Browse DevX
Sign up for e-mail newsletters from DevX


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




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.



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