Skip to content Skip to sidebar Skip to footer

How To Define Public And Private Property In Javascript

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': publi

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 = (functionMyMath() {
    this.Pi = 3.14;
    this.R = 0;

    varMyPrivateProp1 = 15;

    this.MyCalcMethod = function() {
      return R * MyPrivateProp1;
    };

    returnthis;
})();

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.

varPerson = 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 = newPerson();
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;
    }// Setelsereturnthis.val//Get

};

And you could use it like you wanted:

var x = MyMath.Pi * MyMath.R(5);

Solution 4:

Try this code:

// define the MyMathClassfunctionMyMath() {
        functionMyPrivateProp1(){
        //Define get set;
        }
    }
    MyMath.prototype.Pi  = function(){
    //Define getreturn3.14;
    };

    MyMath.prototype.R = function(){
    //Define get and set
    };


    varMyMath = newMyMath();
    var x = MyMath.Pi() * MyMath.R();

References. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Introduction_to_Object-Oriented_JavaScripthttps://developer.mozilla.org/en-US/docs/Web/JavaScript/Guidehttp://javascriptissexy.com/oop-in-javascript-what-you-need-to-know/

Post a Comment for "How To Define Public And Private Property In Javascript"