2012-03-05 126 views
1

我正在使用JavascriptMVC處理我的第一個項目。從JavascriptMVC中的靜態方法獲取靜態屬性的值

我有一個班Foo。

$.Class('Foo',{ 
    // Static properties and methods 
    message: 'Hello World', 
    getMessage: function() { 
     return Foo.message; 
    } 
},{}); 

這工作正常。但如果我不知道班級名稱怎麼辦? 我想是這樣的:

$.Class('Foo',{ 
    // Static properties and methods 
    message: 'Hello World', 
    getMessage: function() { 
     return this.message; 
    } 
},{}); 

,但我不能在靜態屬性中使用這個。 那麼,如何從靜態方法獲取當前類名。

從原型方法很簡單:

​​

,但如何做到這一點的靜態方法?

+0

但是,你知道的類名... **!** – gdoron 2012-03-05 10:14:58

+0

在這種情況下,我知道,但我想編寫一個父類,有一些靜態方法,並使用該靜態方法繼承的類。所以類名將會改變,對於每一個繼承的方法。我不想在每個繼承的類中定義這些靜態方法。 – 2012-03-05 10:17:56

回答

0

事實是,我錯了。以靜態方法使用這個是可能的。 下面是一段代碼片段,它可以幫助理解JavascriptMVC的靜態和原型方法和屬性是如何工作的,以及這兩個的範圍。

$.Class('Foo', 
{ 
    aStaticValue: 'a static value', 
    aStaticFunction: function() { 
    return this.aStaticValue; 
    } 
}, 
{ 
    aPrototypeValue: 'a prototype value', 
    aPrototypeFunction: function() { 
    alert(this.aPrototypeValue); // alerts 'a prototype value' 
    alert(this.aStaticValue); // alerts 'undefined' 
    alert(this.constructor.aStaticValue); // alerts 'a static value' 
    } 
}); 

alert(Foo.aStaticFunction()); // alerts 'a static value' 
var f = new Foo(); 
alert(f.aPrototypeValue); // alerts 'a prototype value' 
f.aPrototypeFunction();