1

When I bring express into my project and create a new express app, I start with these two lines of code

var express = require('express');
var app = express();

This seems to me like express is a function that returns the app object I've created. But later I am able to use express.static() which makes me think that express is an object with the method static.

app.use(express.static('public'));

When I require express it seems to log an object, so I'm curious how express() returns something if it is an object? My final guess would be that express is a function, but because this is javascript, functions are objects and it can have properties as well? Are any of these close to accurate?

Community
  • 1
  • 1
Luke Schlangen
  • 3,722
  • 4
  • 34
  • 69
  • 1
    You can see what express returns here https://github.com/expressjs/express/blob/master/lib/application.js – Cisum Inas Mar 06 '17 at 16:51
  • 2
    yes, in javascript, a function is an object, objects can contain functions, functions can contain objects, functions can contain functions.. etc. The prototypes will define some functionalities one have and not the other by default, different types of objets, but objects – Kaddath Mar 06 '17 at 16:54
  • 1
    Yes. Functions are objects and objects can have arbitrary properties. You might already know that every function has `name`, `bind`, `call`, `apply` and `prototype` properties. `static` is simply a custom property that was added "manually". – Felix Kling Mar 06 '17 at 17:01

1 Answers1

9

Both. It is a function and it's an object - not only in a sense that every function in JavaScript is an object. It actually has some custom properties defined, like express.static, to use it like an normal object.

To demonstrate it let's say that you have a simple module, that exports one function like Express

'use strict';
function x() {
    return 'x';
}
x.a = 1;
x.b = 'b';
x.c = () => 'c';
x.d = {a: 1, b: 2, c: 3};
module.exports = x;

Now when you require your module as, e.g.

var x = require('./x');

you can do:

console.log( x() );

but also:

console.log( x.a );
console.log( x.b );
console.log( x.c() );
console.log( x.d.a );
rsp
  • 107,747
  • 29
  • 201
  • 177