从JavascriptMVC中的静态方法中获取静态属性的值

Get the value of static properties from static methods in JavascriptMVC

本文关键字:属性 静态 静态方法 JavascriptMVC 获取      更新时间:2023-09-26

我正在用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;
    }
},{});

但我不能在静态属性中使用this。那么,如何从静态方法中获取当前类名呢。

从原型方法来看,这很容易:

this.constructor.shortName/fullName.

但是如何在静态方法中实现呢?

事实是,我错了。可以在静态方法中使用this。这里有一个小代码片段,可以帮助理解JavascriptMVC的静态和原型方法和属性是如何工作的,以及this在这两种方法和属性中的作用范围。

$.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();