Reputation: 3211
in the following code
const express = require('express');
const app = express()
app.use(express.static('public'));
express is a function so how it call "express.static('public')" method on it? is it possible in JavaScript to call a function which is inside a function
Upvotes: 11
Views: 1287
Reputation: 9010
You can attach a function as member data to another function (which is what is done in your example).
const express = () => {};
express.static = argument => console.log('argument');
express.static('public'); # console >>> 'public'
However, you cannot readily access a variable that is defined in a function body.
const express = () => {
const static = argument => console.log('argument');
};
express.static('public'); # console >>> Error: undefined in not a function
There is a signifiant difference between member data attached to a function (the first example) and the closure that wraps the body of the function (the second example).
So, to answer your question "is it possible in JavaScript to call a function which is inside a function?" No, this is not readily possible with the important note that this is not what is being done in your example.
Upvotes: 3
Reputation: 518
Actually, it is possible to call a function inside another function in javaScript. So it depends on the condition, Callback is widely used in js
(A callback is a function that is to be executed after another function has finished executing)
function doHomework(subject, callback) {
alert(`Starting my ${subject} homework.`);
callback();
}
function alertFinished(){
alert('Finished my homework');
}
doHomework('math', alertFinished);
And the second example can be Closures
(A closure is a feature in JavaScript where an inner function has access to the outer (enclosing) function's variables)
function outer() {
var b = 10;
function inner() {
var a = 20;
console.log(a+b);
}
return inner;
}
Upvotes: -1
Reputation: 386519
A functions is not only a first class function, but also a first class object and can contain properties.
function foo() {}
foo.bar = function () { console.log('i am bar'); };
foo.bar();
Upvotes: 19