问题描述:

I have an object and i can get all function in it.but i want add function with proto then get all function.how can i do?

var myObj = {

func1:function(){}

};

var myPrototype = {

func2: function(){

}

};

myObj.__proto__ = myPrototype;

alert(Object.getOwnPropertyNames(myObj));

the result is

func1

but i want all the functions

func1,func2

how can i do this??????

网友答案:

As the method name says, Object.getOwnPropertyNames does only get you the own property names, not the inherited ones.

To get those as well, you'd need to apply it on the prototype as well - in fact, on all prototypes. Btw, avoid using the __proto__ property.

var myPrototype = {
    func2: function() {}
};
var myObj = Object.create(myPrototype);
myObj.func1 = function(){};

for (var o=myObj; o!=null; o=Object.getPrototypeOf(o))
    alert(Object.getOwnPropertyNames(o));
网友答案:

tnx. i do it by this function

function getAllMethods(obj) {
  var result = [];
  for (var id in obj) {
    try {
      if (typeof(obj[id]) == "function") {
        result.push(id + ": " + obj[id].toString());
      }
    }
    catch (err) {
    }
  }
  return result;
}
相关阅读:
Top