问题
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 ?
回答1:
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.
回答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:
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.
来源:https://stackoverflow.com/questions/16345006/javascript-how-to-access-static-properties