开发者

Get all functions of an object in JavaScript

开发者 https://www.devze.com 2023-04-07 17:14 出处:网络
For example, Math.mymf开发者_运维问答unc = function (x) { return x+1; } will be treated as a property and when I write

For example,

Math.mymf开发者_运维问答unc = 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?


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]);
}


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.


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.];


console.log(Math) should work.


Object.getOwnPropertyNames() is a good solution


The following example is if you have written a sample script and want to create a button for each function.

<!-- <script src="example.js"></script> -->

<script>
// example.js
function Example_foo() {
  console.log("foo")
}

function Example_bar() {
  console.log("bar")
}

for (const funcName of Object.getOwnPropertyNames(this)) {
  if (funcName.startsWith("Example")) {
    const frag = document.createRange().createContextualFragment(`
      <button onclick="${funcName}()">${funcName}</button><br>
    `)
    document.body.append(frag)
  }
}
</script>

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号