RcBuilder@walla.com
call centre: 054-5614020

javascript private/public

26
Jan
2016
Posted by: RcBuilder  /   Category: class / function / JAVASCRIPT / Object / OOP / prototype   /   No Comments

javascript private/public

data members:

private access
defined using var within the object, can’t be accessed from outside the object

example:

function Person(firstName, lastName) {
var firstName = firstName; // data member
var lastName = lastName; // data member


}

properties:

public access
defined using this, can be accessed from outside

example:

function Person(firstName, lastName) {
this.firstName = firstName; // public property
this.lastName = lastName; // public property


}

notice!
we can define properties using ['property'] syntax as well (see also ‘object properties access using []’)

example:

var users = new Object();
users['Roby'] = { Id: 1, Name: ‘Roby Cohen’, Age: 35 }; // this will be equals to users.Roby = …
users['Avi'] = { Id: 10, Name: ‘Avi Cohen’, Age: 33 };
users['Shirly'] = { Id: 100, Name: ‘Shirly Cohen’, Age: 36 };

console.log(users['Shirly'].Id); // 100
console.log(users.Shirly.Id); // 100

private methods:

private access
defined using the formal way, can’t be accessed from outside the object

example:

function Person(firstName, lastName) {
var firstName = firstName;
var lastName = lastName;

function SayHello(){
console.log(‘HELLO WORLD’);
}
}

public methods:

public access
defined using this, can be accessed from outside

e.g (option 1):

function Person(firstName, lastName) {
var firstName = firstName;
var lastName = lastName;

this.SayHello = function() {
console.log(‘HELLO, My Name is ‘ + firstName + ‘ ‘ + lastName);
}
}

e.g (option 2):

function Person(firstName, lastName) {
var firstName = firstName;
var lastName = lastName;

function SayHello(){
console.log(‘HELLO, My Name is ‘ + firstName + ‘ ‘ + lastName);
}

this.SayHello = SayHello; // expose as public method
}

e.g (option 3): // closure

function Person(firstName, lastName) {
var firstName = firstName;
var lastName = lastName;

return{
SayHello: function () {
alert(‘HELLO, My Name is ‘ + firstName + ‘ ‘ + lastName);
}
}
}

var p = new Person(‘Roby’, ‘Cohen’);
p.SayHello();

Author Avatar

About the Author

בניית אתרים ופתרונות טכנולוגים | RcBuilder

No Comments


  • פיתוח מערכות
  • פתרונות טכנולוגים
  • קידום אתרים
  • בניית אתרים