javascript:如何访问静态属性

前端之家收集整理的这篇文章主要介绍了javascript:如何访问静态属性前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

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

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中的相同代码

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

最佳答案

so I tried to access the static property using the instance ‘constructor’ property

这就是问题,你的实例没有构造函数属性 – 你已经覆盖了整个.prototype对象及其默认属性.相反,使用

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

你也可以通过this.constructor使用User.property1而不是绕道而行.此外,您无法确保您可能希望调用方法的所有实例都将其构造函数属性指向User – 因此可以更好地直接和显式地访问它.

原文链接:https://www.f2er.com/js/429745.html

猜你在找的JavaScript相关文章