Get all functions of an object in JavaScript

前端 未结 4 1775
后悔当初
后悔当初 2021-01-02 14:56

For example,

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

will be treated as a property and when I write

for(var p in         


        
相关标签:
4条回答
  • 2021-01-02 15:36
    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.

    0 讨论(0)
  • 2021-01-02 15:40

    console.log(Math) should work.

    0 讨论(0)
  • 2021-01-02 15:42

    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]);
    }
    
    0 讨论(0)
  • 2021-01-02 15:48

    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.];
    
    0 讨论(0)
提交回复
热议问题