如何在javascript中定义公共和私有属性

时间:2014-01-17 09:39:36

标签: c# javascript oop

我想在JavaScript类中定义公共和私有属性,

在这里,您可以看到我的属性的c#格式。

我的问题是'如何使用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;
    }
}

我想使用这个类:

var x = MyMath.Pi * MyMath.R;

提前感谢您的时间。

4 个答案:

答案 0 :(得分:1)

答案是关闭。

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";

现在您可以创建个人类的实例:

var aPerson = new Person();
console.log(aPerson.publicProperty);
console.log(aPerson.publicFunction());
console.log(aPerson.staticProperty);
console.log(aPerson.localVaraible) // undefined.

答案 1 :(得分:1)

您可以创建一个self-executing函数来创建对象,这样您就可以立即从Javascript中调用变量和方法,而无需创建对象的实例。

示例: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);

注意函数末尾的return this,这是确保将对象传递给myMath变量所必需的。

答案 2 :(得分:0)

您可以创建一个存储两个变量的对象。

示例:

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

};

你可以像你想的那样使用它:

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

答案 3 :(得分:0)

试试这段代码:

  // 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();

参考。 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/