如何获得'获取'属性?

时间:2016-07-20 08:19:51

标签: javascript properties

说我有一些对象:

Org.prototype = {
 constructor  : Org,
 get id(){ return this._id; },
 some_method: function(){},
 etc...

如何检索对象的getter?

2 个答案:

答案 0 :(得分:1)

循环遍历所有属性名称,并向下过滤到属性描述符具有get属性的那些名称。



function Foo() { }

Foo.prototype = { 
  get id() { return this._id; },
  otherfunc() { }
};

function getGetters(obj) {
  var proto = obj.prototype;

  return Object.getOwnPropertyNames(proto)
    .filter(name => Object.getOwnPropertyDescriptor(proto, name).get);
}
    
console.log(getGetters(Foo));




答案 1 :(得分:1)

要获取具有“getter”功能的属性列表,请使用以下带有Object.keysObject.getOwnPropertyDescriptorArray.filter函数的approch:

function Org(){};

Org.prototype = {
    constructor  : Org,
    get id(){ return this._id; },
    some_method: function(){}
};

propList = Object.keys(Org.prototype).filter(function (p) {
    return typeof Object.getOwnPropertyDescriptor(Org.prototype, p)['get'] === "function"
});

console.log(propList);

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/getOwnPropertyDescriptor