简体   繁体   English

可以在JS中用参数调用没有参数的函数吗?

[英]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 = require('foo')?

foo.js foo.js

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

bar.js bar.js

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

route.js route.js

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

TLDR: TLDR:

Yes, it is allowed. 是的,允许。

How it works 这个怎么运作

All functions in js have access to a local variable called arguments . js中的所有函数都可以访问名为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. arguments变量是一个类似数组的对象(看起来像数组,但不是Array类的实例),包含所有传递给函数的参数。 This is basically the js mechanism supporting variable arguments. 这基本上是支持变量参数的js机制。

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. 除了允许您传递比函数定义的参数更多的参数外,js还允许您传递比函数所需的参数更少的参数。 The arguments that you don't pass are simply given the value of undefined . 您不传递的参数仅被赋予undefined的值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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