Reputation: 2053
Is it possible to access properties of a constructor object/function without first creating an instance from it?
For example, let's say I have this constructor:
function Cat() {
this.legs = 4;
};
And now – without creating a new cat instance – I want to know what value of legs
is inside the constructor. Is this possible?
(And I'm not looking for stuff like: var legs = new Cat().legs
. (Let's say the instantiation of a new Cat is super CPU expensive for some reason.))
Upvotes: 7
Views: 298
Reputation: 55623
There's a hundred ways to do this, but the static default pattern below is as good as any of them:
function Cat(opts) {
var options = opts || {};
this.legs == options.legs || Cat.defaults.legs;
};
Cat.defaults = {
legs: 4
}
var myCat = new Cat({legs:3}); //poor guy
var normalNumberOfCatLegs = Cat.defaults.legs;
Upvotes: 1
Reputation: 14054
In short, no you can't access that variable without creating an instance of it, but you can work around it:
Global Variable
Assuming 'legs' may vary as the application runs, you may want to create a "global" variable by assigning legs to 'window', an object that will exist throughout the life of the page:
window.legs = 4; // put this at the top of your script
Then throughout the course of the application, you can change this until you're ready to use it in Cats():
window.legs = user_input;
Global Object
You could even assign an object to window, if you want Cats to have other, alterable attributes:
window.Cat = {};
window.Cat.legs = 4;
window.Cat.has_tail = true;
window.Cat.breeds = ["siamese","other cat breed"];
How to use Globals
Then, when a Cat object is created later on, you can pull the data from window to create an instance of Cat:
function Cat(){
this.legs = window.legs;
//or
this.legs = window.Cat.legs;
}
Upvotes: 0
Reputation: 32783
In your scenario, leg
is an instance variable, which means that an object instance is needed in order to access it.
You can make it a pseudo-class variable
(see class variable in Javascript), you should be able then to access it without calling the function (instantiating the object).
Upvotes: 1
Reputation: 29836
Does something like this count?
function Cat() {
this.legs = 4;
}
var obj = {};
Cat.call(obj);
console.log(obj.legs); // 4
Upvotes: 4
Reputation: 3464
// cat.js
function Cat() {
}
Cat.prototype.legs = 4;
// somescript.js
var legs = Cat.prototype.legs
var cat = new Cat();
console.log(legs, cat.legs); // 4, 4
Upvotes: -3
Reputation: 16544
This is even more expensive:
console.log(parseInt(Cat.toString().match(/this\.legs\s*=\s*(\d+)/)[1]));
Upvotes: 1