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


有这样的事情吗?

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

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

这更加昂贵:

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

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

链接地址: http://www.djcxy.com/p/84580.html

上一篇: 与paper.js同时绘图

下一篇: 在不创建新实例的情况下访问构造函数的属性