【问题标题】:javascript: how to access static propertiesjavascript:如何访问静态属性
【发布时间】:2013-04-27 00:52:18
【问题描述】:

我想使用实例访问静态属性。像这样的

function User(){
    console.log('Constructor: property1=' + this.constructor.property1) ;
}
User.prototype = {
    test: function() {
        console.log('test: property1=' + this.constructor.property1) ;
    }
}    
User.property1 = 10 ;   // STATIC PROPERTY

var inst = new User() ;
inst.test() ;

这是jsfiddle中的相同代码

在我的情况下,我不知道实例属于哪个类,所以我尝试使用实例“构造函数”属性访问静态属性,但没有成功:( 这可能吗 ?

【问题讨论】:

  • 不要在javascript中使用class这个词
  • @Johan:这个链接和这里的任何东西有什么关系?

标签: javascript properties static


【解决方案1】:

所以我尝试使用实例“构造函数”属性访问静态属性

这就是问题所在,您的实例没有 constructor 属性 - 您已经覆盖了整个 .prototype 对象及其默认属性。相反,使用

User.prototype.test = function() {
    console.log('test: property1=' + this.constructor.property1) ;
};

您也可以只使用User.property1 而不是通过this.constructor 绕道而行。此外,您无法确保您可能要调用此方法的所有实例的 constructor 属性都指向 User - 所以最好直接明确地访问它。

【讨论】:

  • 如何从构造函数外部访问静态属性,甚至从静态方法访问?
  • @AlanKis:直接在构造函数上,例如User.property1
【解决方案2】:
function getObjectClass(obj) {
    if (obj && obj.constructor && obj.constructor.toString) {
        var arr = obj.constructor.toString().match(
            /function\s*(\w+)/);

        if (arr && arr.length == 2) {
            return arr[1];
        }
    }

    return undefined;
}

function User(){
     console.log('Constructor: property1=' + this.constructor.property1) ;
 }

User.property1 = 10 ;

var inst = new User() ;

alert(getObjectClass(inst));

http://jsfiddle.net/FK9VJ/2/

【讨论】:

    【解决方案3】:

    或许你可以看看:http://jsfiddle.net/etm2d/

    User.prototype = {
    test: function() {
        console.log('test: property1=' + this.constructor.property1) ;
        }
    } 
    

    似乎有问题,虽然我还没有弄清楚原因。

    【讨论】:

      猜你喜欢
      • 2018-04-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-13
      • 1970-01-01
      • 2021-12-05
      • 2015-05-20
      • 1970-01-01
      相关资源
      最近更新 更多