Javascript类

Javascript类,javascript,class,properties,Javascript,Class,Properties,我是javascript新手。 如何在javascript中声明一个名为username的属性的类。 然后在用户名属性值之后运行一个函数。 在C#中是这样的: public int M_A { get { return m_a; } set { m_a = value; RunFunction(); }

我是javascript新手。
如何在javascript中声明一个名为username的属性的类。
然后在用户名属性值之后运行一个函数。
在C#中是这样的:

public int M_A
    {
        get
        {
             return m_a;
        }
        set
        {
             m_a = value;
             RunFunction();    
        }
     }

您可以这样做:

var M_A = function()
{
    var m_a; //private variable

    this.get = function()
    {
         return m_a;
    }

    this.set = function(value)
    {
         m_a = value;
         RunFunction();    //run some global or private function
         this.runPublic(); // run a public function
    }
 }
然后你可以做:

var ma = new M_A();
ma.set(16);
alert(ma.get()); //alerts `16`

演示:

Javascript没有基于类的继承,它使用基于原型的继承。此外,它不支持getter和setter(在大多数版本中)

下面是编写示例的一种方法:

var ExampleClass = function(){
  var _m_a;//private instance
  this.m_a = function(){
    if(arguments.length){
      _m_a = arguments[0];
    }else{
      return _m_a;
    }
  };
};
用法:

var inst = new ExampleClass();
inst.m_a(5);//provide an argument to set it
console.log(inst.m_a());//no arguments to get it
var inst = new ExampleClass();
inst.set_m_a(5);
console.log(inst.get_m_a());
console.log(inst._m_a);//annoying thing is the private property is accessible
因为我们只是近似一个类系统,实际上有两种方法可以做到这一点。还有一个:

var ExampleClass = function(){
  this._m_a = null;
};
ExampleClass.prototype.get_m_a = function(){
  return this._m_a;
};
ExampleClass.prototype.set_m_a = function(value){
  this._m_a = value;
};
用法:

var inst = new ExampleClass();
inst.m_a(5);//provide an argument to set it
console.log(inst.m_a());//no arguments to get it
var inst = new ExampleClass();
inst.set_m_a(5);
console.log(inst.get_m_a());
console.log(inst._m_a);//annoying thing is the private property is accessible
为了更好地理解原型继承和javascript类系统,请查看以下文章: