How To Define Public And Private Property In Javascript
Solution 1:
You could create a self-executing
function to create your object, this will then allow you to instantly call the variables and methods from your Javascript without having to create an instance of the object.
Example : JSFiddle
var myMath = (function MyMath() {
this.Pi = 3.14;
this.R = 0;
var MyPrivateProp1 = 15;
this.MyCalcMethod = function() {
return R * MyPrivateProp1;
};
return this;
})();
myMath.R = 5;
var x = myMath.Pi * myMath.R;
console.log(myMath.Pi);
console.log(myMath.R);
console.log(myMath.MyPrivateProp1); //This is returned as Undefined because it is a Private Variable to the Object.
console.log(myMath.MyCalcMethod());
console.log(x);
Notice the return this
at the end of the function, this is required to ensure the object is passed to the myMath
variable.
Solution 2:
The answer is closures.
var Person = function () {
var localVariable = "I'm hidden";
this.publicProperty = "example";
this.publicFunction = function () {
// This function has access to the localVariable
// but nothing outside can get to it directly.
console.log(localVariable);
return "aren't I clever?";
}
};
Person.prototype.staticProperty = "A banana";
Now you can create an instance of your person class:
var aPerson = new Person();
console.log(aPerson.publicProperty);
console.log(aPerson.publicFunction());
console.log(aPerson.staticProperty);
console.log(aPerson.localVaraible) // undefined.
Solution 3:
You could create an object which would store the two variables.
Example:
var MyMath = {}; //Create a new object
MyMath.Pi = 3.14;
MyMath.R = function(value){
if(value !== undefined){
this.val=value;
}// Set
else return this.val //Get
};
And you could use it like you wanted:
var x = MyMath.Pi * MyMath.R(5);
Solution 4:
Try this code:
// define the MyMathClass
function MyMath() {
function MyPrivateProp1(){
//Define get set;
}
}
MyMath.prototype.Pi = function(){
//Define get
return 3.14;
};
MyMath.prototype.R = function(){
//Define get and set
};
var MyMath = new MyMath();
var x = MyMath.Pi() * MyMath.R();
References. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Introduction_to_Object-Oriented_JavaScript https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide http://javascriptissexy.com/oop-in-javascript-what-you-need-to-know/
Post a Comment for "How To Define Public And Private Property In Javascript"