Reputation: 1527
I want to define public and private property in JavaScript class,
Here you see c# format of my properties.
My question is 'How can I write these properties with JavaScript':
public class MyMath
{
public static double Pi
{
get {return 3.14;}
}
public static int R {get; set;}
private int MyPrivateProp1 {get; set;}
public double MyCalcMethod()
{
return MyPrivateProp1 * R;
}
}
I want to use this class like:
var x = MyMath.Pi * MyMath.R;
Thanks in advance for your time.
Upvotes: 0
Views: 144
Reputation: 3362
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/
Upvotes: 0
Reputation: 3047
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.
Upvotes: 1
Reputation: 3612
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.
Upvotes: 1
Reputation: 2804
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);
Upvotes: 0