Let me start with some statements
-> (Object instanceof Function)
because object constructor is a function
-> (Function instanceof Object)
because functions are objects
Now my question is : How can I simulate the express.js
object behaviour ?
const express = require("express");
const app = express(); // express here is a function
app.use(express.json()) // now here express is an object
This works fine in nodejs and i believed that express
is basically an object and when you call express()
you reference the object constructor.
However things seem to be a bit different.
Trying to consider it as a class will also fail because you don't instantiate it as new
.
And, if you try to simulate it as a function, you can't simulate it as an object.
I've appended 3 of my attempts to simulate this behavior
// Trying to simulate it with a function
var express = () => {
this.json = () => {console.log("json")}
return {
listen : () =>{ console.log("listen !") },
use : () =>{ console.log("use !") }
}
}
const app = express(); // ok
app.listen(); // ok
app.use(); // ok
express.json(); // fail
// Trying to simulate it with a class
class express{
constructor(){
return {
listen : () => { console.log("listen !") },
use : () => { console.log("use !") }
}
}
json(){console.log("json")}
}
const app = express(); // Class constructor express cannot be invoked without 'new'",
app.listen();
app.use();
express.json(); // not instanciated
// Trying to simulate it as an object
var express = {
constructor : ()=>{ // does not overwrite constructor
return {
listen : () =>{ console.log("listen !") },
use : () =>{ console.log("use !") }
}
},
json : ()=>{console.log("json")}
}
const app = express(); // "message": "Uncaught TypeError: express is not a function",
app.listen();
app.use();
express.json()