列出(计算)原型函数

时间:2016-10-12 20:58:33

标签: javascript

例如我有一个简单的对象:

var a = {};

是否可以计算或列出所有关闭此对象原型函数(如“toString”,“构造函数”)?

计算对象'a'函数:

var a = {};
var prototypeFunctions = 0;
var props = Object.getOwnPropertyNames(a.constructor.prototype);

for(var i=0; i<props.length; i++){
    if(a.constructor.prototype[props[i]] instanceof Function){
        prototypeFunctions++;
    }
}

console.log("Number of object 'a' prototype functions: ", prototypeFunctions);

1 个答案:

答案 0 :(得分:3)

您可以在原型上使用Object.getOwnPropertyNames

例如:

&#13;
&#13;
var a = {};
console.log(Object.getOwnPropertyNames(a.constructor.prototype));
&#13;
&#13;
&#13;

输出:

[
  "__defineGetter__",
  "__defineSetter__",
  "hasOwnProperty",
  "__lookupGetter__",
  "__lookupSetter__",
  "constructor",
  "toString",
  "toLocaleString",
  "valueOf",
  "isPrototypeOf",
  "propertyIsEnumerable",
  "__proto__"
]

请注意,这会列出原型的所有直接属性,而不是从父级继承的属性。