简体   繁体   中英

How to find out parameters of a native Javascript function

I want a generic way to find out the required parameters by a any javascript function including natives ones, but I'm unable to find one. I've seen this stackoverflow link, but it works only for functions that we define. toString() doesn't tell us about the function parameters of native functions like window.setTimeout() :

How to get function parameter names/values dynamically from javascript

I'm specifically interested in the GreaseMonkey methods like GM_setValue etc. , which behave similarly and don't show there parameters when used with toString() (I want to validate that a method passed to me has two parameters)

You cannot do this.

You can check how many named parameters a function accepts by inspecting the function's length property:

(function testFn (arg1, arg2) {}).length // Will be 2

Or you can convert the function's body into string and parse the text.

However, a named function parameter does not correlate in any way to a required parameter. Consider the following:

function testFn (arg1, arg2) {
  arg1 = arg1 || 'some default'
  arg2 = arg2 || true
}

// Both work fine
testFn() // No args passed
testFn('customValue', false) // Args passed

function anotherFn () {
  var arg1 = arguments[0] // Discouraged! Just an example
  arg1.toString() // Do stuff with a required arg1 argument
}

// This will throw at you!
anotherFn()

Instead of validating that a function has two arguments, simply validate that the function behaves to your expectations in a test. In general, though, you should only test that what you just got is indeed a function and then simply call it. The responsibility of using the arguments you give to it should be ensured at the receiver (the function you just called), not in the caller.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM