Access to the constructor property without creating a new instance

Is it possible to access the properties of an object / constructor 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 instance of cat . I want to know what the meaning of legs is inside the constructor. Is it possible?

(And I'm not looking for things like: var legs = new Cat().legs . (Let's say the instance of the new Cat is for some reason superior to the CPU.))

+7
javascript
source share
6 answers

Is something like this counting?

 function Cat() { this.legs = 4; } var obj = {}; Cat.call(obj); console.log(obj.legs); // 4 
+4
source share

In your script, leg is an instance variable, which means that an object instance is needed to access it.

You can do this a pseudo- class variable (see the class variable in Javascript ), then you can access it without calling a function (creating an instance of an object).

+1
source share

This is even more expensive:

 console.log(parseInt(Cat.toString().match(/this\.legs\s*=\s*(\d+)/)[1])); 
+1
source share

There are a hundred ways to do this, but the default static template 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; 
+1
source share

In short, no, you cannot access this variable without creating it, but you can get around it:

Global variable

Assuming that the “legs” may vary as the application launches, you may need to create a “global” variable by assigning a “window” to the legs, 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 entire application, you can change this until you are ready to use it in Cats ():

 window.legs = user_input; 

Global object

You can even assign an object to a window if you want Cats to have other mutable 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 the Cat object is created later, you can pull data from the window to create a Cat instance:

 function Cat(){ this.legs = window.legs; //or this.legs = window.Cat.legs; } 
0
source share
 // 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 
-3
source share

All Articles