2011-06-06 80 views
0

我是javascript新用戶。
如何在javascript中聲明一個類,例如使用名爲username的屬性。
然後在運行函數的用戶名屬性值後運行。
在C#中是這樣的:
Javascript class

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

回答

3

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 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.set_m_a(5); 
console.log(inst.get_m_a()); 
console.log(inst._m_a);//annoying thing is the private property is accessible 

爲了更好地理解原型繼承和JavaScript類系統中,檢查出這些職位:

2

你可以做這樣的事情:

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` 

演示:http://jsfiddle.net/maniator/72bnW/