最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - calling a function on a function is it possible? - Stack Overflow

programmeradmin1浏览0评论

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

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

Share Improve this question asked Dec 22, 2018 at 9:37 Ehsan SarsharEhsan Sarshar 3,2111 gold badge28 silver badges46 bronze badges 1
  • good old days of learning Javascript – Ehsan Sarshar Commented Aug 2, 2023 at 14:17
Add a comment  | 

3 Answers 3

Reset to default 19

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();

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.

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;
}
发布评论

评论列表(0)

  1. 暂无评论