JAVA SCRIPT- Keeping Object Members Private - Web Development and Design | Tutorial for Java, PHP, HTML, Javascript JAVA SCRIPT- Keeping Object Members Private - Web Development and Design | Tutorial for Java, PHP, HTML, Javascript


Post Top Ad

Post Top Ad

Wednesday, December 26, 2018

JAVA SCRIPT- Keeping Object Members Private

Keeping Object Members Private


You want to keep one or more object properties private, so they can’t be accessed outside the object instance. 


When creating the private data members, do not use the this keyword with the member:
function Tune(song,artist) {
 var title = song;
 this.concat = function() {
 return title + " " + artist;
var happySongs = [];
happySongs[0] = new Tune("Putting on the Ritz", "Ella Fitzgerald");
console.log(happySongs[0].title); // undefined
// prints out correct title and artist


Variables in the object constructor (the function body), are not accessible outside the object unless they’re attached to that object using this. If they’re redefined using the var keyword or passed in as parameters only, the Tune’s inner function, the concat() method, can access these now-private data members.

 This type of method—one that can access the private data members, but is, itself, ex‐ posed to public access via this—has been termed a privileged method by Douglas Crockford, the father of JSON (JavaScript Object Notation).: This pattern of public, private, and privileged members is possible because JavaScript has closures.

What this means is that an inner function always has access to the vars and parameters of its outer function, even after the outer function has returned. This is an extremely powerful property of the language [. . . .] Private and privileged members can only be made when an object is constructed. Public members can be added at any time. Be aware, though, that the privacy of the variable is somewhat illusory. One can easily assign a value to that property outside the constructor function, and overwrite the pri‐ vate data:

happySongs[0].title = 'testing';
console.log(happySongs[0].title); // testing

However, the “privacy” of the data isn’t meant to ensure security of the object. It’s a contract with the developer, a way of saying, “This data isn’t meant to be accessed directly, and doing so will probably mess up your application.” As such, developers also typically use a naming convention where private data members begin with an underscore, to highlight that they aren’t meant to be accessed or set directly:

function Tune(song,artist) {
 var _title = song;
 this.concat = function() {
 return _title + " " + artist;

No comments:

Post a Comment

Post Top Ad