关于顶级功能的困惑

我刚刚开始学习JavaScript和Node。由于来自Python背景,因此几乎没有什么事情可做。例如,要在Express中创建服务器,我们将使用:

const express = require("express");

const app = express();
...

它在哪里说

/**
 * Creates an Express application. The express() function is a top-level function exported by the express module.
 */

I don't understand why express() is a function. If the same thing should be done in Python, it will be done like:

from flask import Flask
app = Flask(__name__)

它在哪里说

首先,我们导入了Flask类。此类的实例将是我们的WSGI应用程序。      接下来,我们创建此类的实例。那个...

这是我对编程的一般理解。大多数时候,我们从库中导入一些类并创建一个对象,然后,我们操纵其方法。在javascript中,我发现它与函数,构造函数等混淆。构造函数与类相同吗?

评论
陌若惜
陌若惜

When you import express, what you get is a factory function. A factory function is a function that, when you call it, it creates an object for you. It's similar to using new with a constructor, but a factory function doesn't expose the constructor directly or the class directly. It just exposes you to a function that when you call it, it creates an object that you can then interact with by calling methods.

想象一下这幕后花絮:

class Express {
    constructor() {
        ...
    }
    get() {
        ...
    }
    post() {
        ...
    }
    use() {
        ...
    }
}

// factory function
function createExpressInstance() {
   let obj = new Express();
   // maybe do some other setup on the object
   return obj;
}

// define function that will be referenced as express.static()
createExpressIntance.static = function() {
   ...
}

// export the factory function
module.exports = createExpressInstance;

A factory function is one design pattern for an API that can create new objects. Rather than exposing the class definition directly or the exporting the constructor directly, it "hides" the actual implementation. You call a function and get an object back.

There are some specific situations where a factory function is a preferred way of constructing a new object (particularly when asynchronous things might be involved in constructing the object), but in other situations (like this), it's just a style choice for how to write the code and how to design a public API.

点赞
评论