In JavaScript, you can retrieve all the methods of an object by inspecting its properties and checking which ones are functions. This is useful for debugging or dynamically analysing objects.
[Approach 1]: Use typeof operator and filter() Methods
- Create a function that takes an object as input.
- Use typeof operator, which checks if the type of object is a function or not.
- If the type of object is a function then it returns the object.
function Obj() {
this.m1 = function M1() {
return "From M1";
}
this.m2 = function M2() {
return "From M2";
}
}
function getAllMethods(obj = this) {
return Object.keys(obj)
.filter((key) => typeof obj[key] === 'function')
.map((key) => obj[key]);
}
function print() {
console.log(getAllMethods(new Obj()));
}
print();
Output
[ [Function: M1], [Function: M2] ]
[Approach 2]: Use typeof operator and for-in loop
Use the for-in loop to iterate over all properties of an object and check each one with the typeof operator to identify methods.
- Create a function that takes an object as input.
- Usetypeof operator, which checks if the type of object is a function or not. This example also checks if any error occurred or not and if occurred then handle it properly.
- If the type of Object is a function then return it.
function Obj() {
this.m1 = function M1() {
return "From M1";
}
this.m2 = function M2() {
return "From M2";
}
}
function getAllMethods(obj) {
let result = [];
for (let id in obj) {
try {
if (typeof (obj[id]) == "function") {
result.push(id + ": " + obj[id].toString());
}
} catch (err) {
result.push(id + ": Not accessible");
}
}
return result;
}
function print() {
console.log(getAllMethods(new Obj()).join("\n"));
}
print();
Output
m1: function M1() {
return "From M1";
}
m2: function M2() {
return "From M2";
}