如何在javascript中定义公共和私有属性 [英] How to define public and private property in javascript

查看:61
本文介绍了如何在javascript中定义公共和私有属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to define public and private property in JavaScript class,

在这里你可以看到我的属性的 c# 格式.

Here you see c# format of my properties.

我的问题是如何使用 JavaScript 编写这些属性":

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;

提前感谢您的时间.

推荐答案

您可以创建一个 self-executing 函数来创建您的对象,这将允许您立即从您的 Javascript 无需创建对象的实例.

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.

示例: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变量所必需的.

Notice the return this at the end of the function, this is required to ensure the object is passed to the myMath variable.

这篇关于如何在javascript中定义公共和私有属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆