简体   繁体   中英

Accessing property of constructor without creating new instance

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.))

Does something like this count?

function Cat() {
  this.legs = 4;
}

var obj = {};
Cat.call(obj);
console.log(obj.legs); // 4

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).

这甚至更贵:

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

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;

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;
}
// 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

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