javascript:如何访问静态属性 [英] javascript: how to access static properties

查看:60
本文介绍了javascript:如何访问静态属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

 功能User(){console.log('Constructor:property1 ='+ this.constructor.property1);}User.prototype = {测试:function(){console.log('test:property1 ='+ this.constructor.property1);}}User.property1 = 10;//静态属性var inst = new User();inst.test(); 

jsfiddle

中的代码与此相同

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

解决方案

所以我尝试使用实例的'constructor'属性访问静态属性

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

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

您也可能只使用 User.property1 而不是通过 this.constructor 绕行.同样,您也不能确保可能要在其上调用此方法的所有实例都具有指向 User constructor 属性-因此更好地直接和显式访问它./p>

I want to access a static property using an instance. Something like this

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

Here is the same code in a jsfiddle

In my situation I don't know which class the instance belongs to, so I tried to access the static property using the instance 'constructor' property, without success :( Is this possible ?

解决方案

so I tried to access the static property using the instance 'constructor' property

That's the problem, your instances don't have a constructor property - you've overwritten the whole .prototype object and its default properties. Instead, use

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

And you also might just use User.property1 instead of the detour via this.constructor. Also you can't ensure that all instances on which you might want to call this method will have their constructor property pointing to User - so better access it directly and explicitly.

这篇关于javascript:如何访问静态属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆