Get all functions of an object in JavaScript

不问归期 提交于 2019-11-30 15:09:55

问题


For example,

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

will be treated as a property and when I write

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

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


回答1:


Object.getOwnPropertyNames(Math); is what you are after.

This logs all of the properties provided you are dealing with an EcmaScript 5 compliant browser.

var objs = Object.getOwnPropertyNames(Math);
for(var i in objs ){
  console.log(objs[i]);
}



回答2:


var functionNames = [];

Object.getOwnPropertyNames(obj).forEach(function(property) {
  if(typeof obj[property] === 'function') {
    functionNames.push(property);
  }
});

console.log(functionNames);

That gives you an array of the names of the properties that are functions. Accepted answer gave you names of all the properties.




回答3:


The specification doesn't appear to define with what properties the Math functions are defined with. Most implementations, it seems, apply DontEnum to these functions, which mean they won't show up in the object when iterated through with a for(i in Math) loop.

May I ask what you need to do this for? There aren't many functions, so it may be best to simply define them yourself in an array:

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



回答4:


console.log(Math) should work.



来源:https://stackoverflow.com/questions/7548291/get-all-functions-of-an-object-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!