问题
I'm trying to learn express.js and then i encountered these statements.
const express = require('express');
const app = express();
So now how is it possible to write this variable "express" as "express()". Is it possible to do this with any type of variable?
回答1:
Functions are first-class objects in JavaScript, they aren't special like they are in some other languages. They're just objects that are callable. Since they're objects, you can pass them around:
function example() {
console.log("Hi there");
}
const e = example;
e(); // "Hi there"
You can also put additional properties on them (something that Express also does). Here's an example:
function example() {
console.log("Hi there");
}
example.prop = 42;
const e = example;
e(); // "Hi there"
console.log(example.prop); // 42
console.log(e.prop); // 42 -- since `e` and `example` both refer to the same function
Is it possible to do this with any type of variable?
JavaScript variables don't have a type as they do in strongly-typed languages. The value the variable holds has a type, but the variable doesn't; a variable can hold a number one moment, a string the next, a function after that...
function example() {
console.log("Hi there");
}
let e = example;
e(); // "Hi there"
e = 42;
console.log(e); // 42
e = "Hi there";
console.log(e); // "Hi there"
If you want variables, parameters, and such to have types (so you can't put a string in a variable that's expected to contain a number), consider using TypeScript, Flow, or even just JSDoc combined with robust IDE support. These layer a type system on top of JavaScript (to varying degrees).
Getting back to your question: You can do it with any variable, but not with any type of value. You can't call a number:
let e = 42;
e(); // TypeError: e is not a function
You can only call functions or other host-provided callable objects¹ (which don't absolutely have to be true functions, but it's uncommon now for hosts to provide callable objects that aren't actual functions, it was problematic).
¹ Specifically, in spec terms, any object that supports the [[Call]] internal operation.
回答2:
It is not possible to do this with any variable but there is something called arrow functions for example
const test = () => {}
and you can call this function by saying
test()
within () it takes input and within {} you specify what it does or returns
require fetches whatever you specified so i'm guessing it is equal to a function
To do this with any variable it must be an arrow function. Hope I helped you!
回答3:
Definitely yes, you are talking about JavaScript inline functions, check this out!
For example, you can do:
function example() {
return 1;
}
const execute = example();
console.log(execute) // returns 1
来源:https://stackoverflow.com/questions/66075802/how-it-is-possible-to-use-a-variable-as-a-function-in-javascript