Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to print all methods of an object? [duplicate]

Tags:

javascript

Is there a way to print all methods of an object in JavaScript?

like image 821
Fabien Avatar asked Sep 30 '08 10:09

Fabien


People also ask

How do you print all the properties of an object in Python?

Use Python's vars() to Print an Object's Attributes The dir() function, as shown above, prints all of the attributes of a Python object.

How do you print all elements of a class in Python?

In Python, this can be achieved by using __repr__ or __str__ methods. __repr__ is used if we need a detailed information for debugging while __str__ is used to print a string version for the users. Important Points about Printing: Python uses __repr__ method if there is no __str__ method.

How do I print the contents of an object in JavaScript?

stringify() method is used to print the JavaScript object. JSON. stringify() Method: The JSON. stringify() method is used to allow to take a JavaScript object or Array and create a JSON string out of it.


2 Answers

Sure:

function getMethods(obj) {   var result = [];   for (var id in obj) {     try {       if (typeof(obj[id]) == "function") {         result.push(id + ": " + obj[id].toString());       }     } catch (err) {       result.push(id + ": inaccessible");     }   }   return result; } 

Using it:

alert(getMethods(document).join("\n")); 
like image 81
troelskn Avatar answered Sep 20 '22 16:09

troelskn


If you just want to look what is inside an object, you can print all object's keys. Some of them can be variables, some - methods.

The method is not very accurate, however it's really quick:

console.log(Object.keys(obj)); 
like image 34
mrded Avatar answered Sep 21 '22 16:09

mrded