Get all object functions in JavaScript

For instance,

Math.mymfunc = function (x) { return x+1; } 

will be considered as a property and when I write

 for(var p in Math.__proto__) console.log(p) 

will be shown. But the rest of the Math functions will not. How can I get all the functions of a Math object?

+6
source share
4 answers

Object.getOwnPropertyNames(Math); - This is what you need.

This logs all properties if you are dealing with a browser compatible with EcmaScript 5.

 var objs = Object.getOwnPropertyNames(Math); for(var i in objs ){ console.log(objs[i]); } 
+11
source
 var functionNames = []; Object.getOwnPropertyNames(obj).forEach(function(property) { if(typeof obj[property] === 'function') { functionNames.push(property); } }); console.log(functionNames); 

This gives you an array of property names that are functions. The accepted answer gave you the names of all the properties.

+3
source

The specification does not determine what properties Math functions are defined with. Apparently, most implementations apply DontEnum to these functions, which means that they will not be displayed in the object when repeated using the for(i in Math) loop.

May I ask why you need to do this? There are not many functions, so it’s best to just define them in an array:

 var methods = ['abs', 'max', 'min', ...etc.]; 
+2
source

console.log(Math) should work.

0
source

Source: https://habr.com/ru/post/898021/


All Articles