Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get an object's methods?

Is there a method or propertie to get all methods from an object? For example:

function foo() {} foo.prototype.a = function() {} foo.prototype.b = function() {}  foo.get_methods(); // returns ['a', 'b']; 

UPDATE: Are there any method like that in Jquery?

Thank you.

like image 347
thom Avatar asked Apr 30 '11 15:04

thom


People also ask

How do you find the method of an object?

The first method to find the methods is to use the dir() function. This function takes an object as an argument and returns a list of attributes and methods of that object. From the output, we can observe that it has returned all of the methods of the object.

What are an object's methods?

a method is an action which an object is able to perform. sending a message to an object means asking the object to execute or invoke one of its methods.

How do you print an object method?

To print all methods of an object, we can use Object. getOwnPropertyNames and check if the corresponding value is a function. The Object. getOwnPropertyNames() method returns an array of all properties (enumerable or not) found directly upon a given object.


2 Answers

function getMethods(obj) {     var res = [];     for(var m in obj) {         if(typeof obj[m] == "function") {             res.push(m)         }     }     return res; } 
like image 147
Makram Saleh Avatar answered Sep 20 '22 06:09

Makram Saleh


Remember that technically javascript objects don't have methods. They have properties, some of which may be function objects. That means that you can enumerate the methods in an object just like you can enumerate the properties. This (or something close to this) should work:

var bar for (bar in foo) {     console.log("Foo has property " + bar); } 

There are complications to this because some properties of objects aren't enumerable so you won't be able to find every function on the object.

like image 31
ReinstateMonica Larry Osterman Avatar answered Sep 19 '22 06:09

ReinstateMonica Larry Osterman