简体   繁体   中英

Can a function without an argument be called with an argument in JS?

I am trying to figure out what this piece of code is doing, and how this is working. How is let foo = require('foo') being called when it doesn't take any argument?

foo.js

module.export = async () => { do something and return response(200) }

bar.js

let foo = require('foo')
module.exports = {
  foo: async (req) => { return foo(req) }
}

route.js

let api = required('api')
let bar = required('bar')
module.exports = api => {
  api.get('/foo', async req => await bar.foo(req))
}

TLDR:

Yes, it is allowed.

How it works

All functions in js have access to a local variable called arguments . The arguments variable is an array-like object (something that looks like an array but is not an instance of the Array class) containing all arguments passed to the function. This is basically the js mechanism supporting variable arguments.

Example:

function a () {
    for (x=0; x<arguments.length); x++) {
        console.log(arguments[x]);
    }
}

In addition to allowing you to pass more arguments than what's defined by a function js also allows you to pass fewer arguments that what's required by a function. The arguments that you don't pass are simply given the value of undefined .

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