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 ?
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 ?
Share Improve this question asked May 2, 2013 at 18:18 Jeanluca ScaljeriJeanluca Scaljeri 29.2k66 gold badges233 silver badges380 bronze badges 2- dont use the word class in javascript – Maizere Pathak.Nepal Commented May 2, 2013 at 18:20
- @Johan: How is that link related to anything here? – Bergi Commented May 2, 2013 at 18:28
3 Answers
Reset to default 5so 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/FK9VJ/2/
Perhaps you may have a look at: http://jsfiddle/etm2d/
User.prototype = {
test: function() {
console.log('test: property1=' + this.constructor.property1) ;
}
}
seems to be problematic, although i haven't yet figured out why.