Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing property of constructor without creating new instance

Tags:

javascript

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

like image 744
Kristoffer K Avatar asked Apr 21 '15 13:04

Kristoffer K


2 Answers

Does something like this count?

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

var obj = {};
Cat.call(obj);
console.log(obj.legs); // 4
like image 109
Amir Popovich Avatar answered Sep 28 '22 06:09

Amir Popovich


This is even more expensive:

console.log(parseInt(Cat.toString().match(/this\.legs\s*=\s*(\d+)/)[1]));
like image 45
devnull69 Avatar answered Sep 28 '22 07:09

devnull69