Javascript has no special syntax to denote private properties or methods. But the same effect can be achieved declaring variables or methods with keyword "var" in function or object scope. Below is an example concentrate on this concept:
// In MyObject all properties and methods are public, as there is no use of "var" inside object
function MyObject() {
this.name = "Ravi Kumar";
this.getName = function() {
console.log(this.name) }
}
var myObj = new MyObject()
myObj.getName() // Ravi Kumar
myObj.getName() // Ravi Kumar
console.log(myObj.name) // Ravi Kumar
//Adding var will make name public
function MyObject() {
var name = "Ravi Kumar";
this.getName = function() {
console.log(name) }
}
var myObj = new MyObject()
myObj.getName() // Ravi Kumar
myObj.getName() // Ravi Kumar
console.log(myObj.name) // undefined
Where as while returning private members of type Object or Array, you should note that, when we pass Objects or Array we pass it by reference. Hence while returning private Objects and Arrays we would be exposing them to further altercations. So for being on the safer side, while returning general utility for clone/copy should be used, with that whatever we return will not have any relation with the Private member.
Privileged Methods: Privileged Methods is nothing but method created in local scope of variables which has access to those variables. In above example getName is a privileged method.
If you want to declare private members using object literal you should wrap it with immediate function as follows.
var myObj=(function(){
var name="Ravi Kumar";
return {
getName:function(){
return name;
}
}
}())
myObj.getName() // Ravi Kumar
No comments:
Post a Comment