开发者

Javascript class

I'm new in javascript.

How can I decl开发者_如何学Pythonare a class in javascript for example with property that named username.

then after username property valued a function is run.

In C# it is something like this :

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


Javascript doesn't have a class-based inheritance, it uses a prototype-based. Additionally, it doesn't provide support for getters and setters (in most versions).

Here would be one way to write your example:

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

Usage:

var inst = new ExampleClass();
inst.m_a(5);//provide an argument to set it
console.log(inst.m_a());//no arguments to get it

Since we're just approximating a class system, there's actually a couple ways to do this. Here's another:

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

Usage:

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

For a better understanding of prototypal inheritance and javascript class systems, check out these posts:

  • Simple JavaScript Inheritance by John Resig (creator of jQuery)
  • Classical Inheritance in JavaScript by Douglas Crockford
  • JS Class - a Class framework for javascript


You can do something like this:

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
    }
 }

Then you can do:

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

Demo: http://jsfiddle.net/maniator/72bnW/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜