简体   繁体   中英

javascript: how to access static properties

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.

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/

Perhaps you may have a look at: http://jsfiddle.net/etm2d/

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

seems to be problematic, although i haven't yet figured out why.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM