In JavaScript, an object's methods are properties whose values are functions. We can retrieve these methods by checking the type of each property and selecting those whose type is "function".
- Use the typeof operator to identify function-valued properties.
- Use Object.keys() to retrieve the object's own enumerable properties.
- Use a for...in loop to iterate through object properties.
- Methods defined on the prototype are not returned by Object.keys().
Approach 1: Using typeof Operator and filter()
The idea is to use Object.keys() to get the object's properties and then use filter() to select only those properties whose values are functions. Finally, map() returns the corresponding methods.
Example: Gets all methods defined directly inside the object.
function Obj() {
this.m1 = function M1() {
return "From M1";
};
this.m2 = function M2() {
return "From M2";
};
}
function getAllMethods(obj) {
return Object.keys(obj)
.filter(key => typeof obj[key] === "function")
.map(key => obj[key]);
}
console.log(getAllMethods(new Obj()));
Output
[ [Function: M1], [Function: M2] ]
Approach 2: Using typeof Operator and for...in Loop
The idea is to use a for-in loop to iterate over the object's enumerable properties and check each property's type using the typeof operator. If the property contains a function, its name and function definition are added to the result.
Example: Gets the names and definitions of all accessible methods.
function Obj() {
this.m1 = function M1() {
return "From M1";
};
this.m2 = function M2() {
return "From M2";
};
}
function getAllMethods(obj) {
let result = [];
for (let key in obj) {
try {
if (typeof obj[key] === "function") {
result.push(key + ": " + obj[key].toString());
}
} catch (err) {
result.push(key + ": Not accessible");
}
}
return result;
}
console.log(getAllMethods(new Obj()).join("\n"));
Output
m1: function M1() {
return "From M1";
}
m2: function M2() {
return "From M2";
}
Note: Object.keys() only returns the object's own enumerable properties, while for...in can also iterate over enumerable properties inherited through the prototype chain. Therefore, the choice of approach depends on whether inherited methods should also be included.