javascript:如何访问静态属性 [英] javascript: how to access static properties
问题描述
我想使用实例访问静态属性.像这样
功能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();
中的代码与此相同在我的情况下,我不知道实例属于哪个类,因此我尝试使用实例的构造函数"属性访问静态属性,但未成功:(这可能吗 ?
所以我尝试使用实例的'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屋!