简体   繁体   English

当我需要“express”时,我需要知道它是一个对象还是一个函数

[英]when I require "express" I need to know if its an object or function

Given my code鉴于我的代码

const express = require("express")
const app = express()


console.log(typeof app)
console.log(typeof express)

My terminal tells me that both of these variables are functions!我的终端告诉我这两个变量都是函数!

This makes no sense to me because I can access properties from each of them as if they were objects and yet when I do a typeof in console.log my terminal tells me they are both functions.这对我来说毫无意义,因为我可以从每个属性中访问它们,就好像它们是对象一样,但是当我在 console.log 中执行 typeof 时,我的终端告诉我它们都是函数。

Can someone please explain to me what these variables are and why its possible to access their properties as if they were objects?有人可以向我解释这些变量是什么以及为什么可以像访问它们一样访问它们的属性吗?

According to the docs , The express() function is a top-level function exported by the express module.根据文档, express() 函数是 express 模块导出的顶级函数。

It is similar like having Class and Object .它类似于拥有ClassObject The variable express that you are declaring is acting as a class , while the variable app is the object of it which is used.您声明的变量express充当class ,而变量app是它使用的object

when I require “express” I need to know if its an object or function当我需要“express”时,我需要知道它是一个对象还是一个函数

It's both.两者都是。 Functions in Javascript are objects. Javascript 中的函数是对象。

Without getting technical, express is a factory function that creates an app instance and app is an express instance.无需了解技术, express是一个创建应用程序实例的工厂函数,而app是一个 express 实例。 Now, technically, both express and app are functions.现在,从技术上讲, expressapp都是函数。 But, functions in Javascript are objects and can have properties.但是,Javascript 中的函数是对象并且可以具有属性。 The express object has static properties. express 对象具有静态属性。 The app object behaves much like an instance of the express class. app对象的行为很像 express 类的实例。 It has both methods and instance data.它同时具有方法和实例数据。

Now, getting a little more technical...现在,获得更多的技术...

const express = require('express') gets you a function and that function is also an object and has properties. const express = require('express')您提供一个函数,该函数也是一个对象并具有属性。

This specific function is a factory function that creates an app object when you call it that is also a function that has properties.这个特定的函数是一个工厂函数,当你调用它时它会创建一个app对象,它也是一个具有属性的函数。

So, express also has properties that can be used such as:因此, express还具有可以使用的属性,例如:

express.static
express.json
express.urlencoded

And, it can be called as in:而且,它可以被称为:

const app = express();

Likewise, app is a function that has properties too.同样, app也是一个具有属性的函数。 It can be used as a function as in:它可以用作函数,如下所示:

const server = http.createServer(app);
server.listen(80);

Or, it can be used like an object as in:或者,它可以像对象一样使用,如下所示:

const server = app.listen(80);

If you output this:如果你输出这个:

console.log(typeof express);
console.log(typeof app);

You will see this:你会看到这个:

function
function

They are both functions.它们都是函数。 But, functions in Javascript are objects too and can have properties.但是,Javascript 中的函数也是对象并且可以具有属性。

So, you can do things like this:所以,你可以做这样的事情:

function myFunction() {
    return "ok";
}

myFunction.greeting = "Hello";

console.log(myFunction());                 // "ok"
console.log(myFunction.greeting);         // "Hello"

Looking further at both express and app , if you did this:进一步查看expressapp ,如果你这样做:

console.log(Object.getOwnPropertyNames(express));

You would get this:你会得到这个:

[
  'length',         'name',
  'prototype',      'application',
  'request',        'response',
  'Route',          'Router',
  'json',           'query',
  'raw',            'static',
  'text',           'urlencoded',
  'bodyParser',     'compress',
  'cookieSession',  'session',
  'logger',         'cookieParser',
  'favicon',        'responseTime',
  'errorHandler',   'timeout',
  'methodOverride', 'vhost',
  'csrf',           'directory',
  'limit',          'multipart',
  'staticCache'
]

And, this:和这个:

console.log(Object.getOwnPropertyNames(app));

would get this:会得到这个:

[
  'length',          'name',            'prototype',
  'constructor',     '_events',         '_eventsCount',
  '_maxListeners',   'setMaxListeners', 'getMaxListeners',
  'emit',            'addListener',     'on',
  'prependListener', 'once',            'prependOnceListener',
  'removeListener',  'off',             'removeAllListeners',
  'listeners',       'rawListeners',    'listenerCount',
  'eventNames',      'init',            'defaultConfiguration',
  'lazyrouter',      'handle',          'use',
  'route',           'engine',          'param',
  'set',             'path',            'enabled',
  'disabled',        'enable',          'disable',
  'acl',             'bind',            'checkout',
  'connect',         'copy',            'delete',
  'get',             'head',            'link',
  'lock',            'm-search',        'merge',
  'mkactivity',      'mkcalendar',      'mkcol',
  'move',            'notify',          'options',
  'patch',           'post',            'propfind',
  'proppatch',       'purge',           'put',
  'rebind',          'report',          'search',
  'source',          'subscribe',       'trace',
  'unbind',          'unlink',          'unlock',
  'unsubscribe',     'all',             'del',
  'render',          'listen',          'request',
  'response',        'cache',           'engines',
  'settings',        'locals',          'mountpath',
  'router'
]

So, you can see they each have a lot of properties in addition to being functions.所以,你可以看到它们除了是函数之外还有很多属性。


Ok please tell me if I have got this correct.好的,请告诉我是否正确。 1) When I do this… const express = require(“express”) I store a “Class” into the express variable. 1) 当我这样做时…… const express = require(“express”)我将一个“类”存储到 express 变量中。 2) Then when I do this… express.json() I am accessing the json() function inside the express class ? 2)然后当我这样做时…… express.json()我正在访问 express 类中的json()函数?

As I said in my answer above that express variable represents a factory function.正如我在上面的回答中所说, express变量代表一个工厂函数。 That's a function that, when called, creates an object for you.这是一个函数,当被调用时,它会为你创建一个对象。 It's a different way of creating an object from directly calling a constructor as in new myObj() .这是一种通过直接调用构造函数来创建对象的不同方式,就像在new myObj() express.json is a function that, when called, creates a middleware function for you that uses the parameters you passed the function. express.json是一个函数,在调用时,它会为您创建一个中间件函数,该函数使用您传递给函数的参数。

The Express architecture differs a bit from a pure class style architecture. Express 体系结构与纯类样式体系结构略有不同。 It uses a factory function that creates an instance (essentially of a class).它使用一个工厂函数来创建一个实例(本质上是一个类)。 And, then the app represents that instance, but also works as a request handler on its own.然后,该app代表该实例,但也可以单独用作请求处理程序。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我需要知道 express 才能使用 Javascript 吗? - Do I need to know express to use Javascript? 我有一个 function 我需要知道它什么时候会返回 true 而不是 false - I have a function and I need to know when it will return true and not false 意外的令牌 { 当我需要“express-fileupload”时 - Unexpected token { when I require "express-fileupload" 我使用babel时是否需要js? - Do I need require js when I use babel? Express.js,什么需要返回,为什么我们需要将变量作为函数访问以获取其值? - Express.js, what does require return and why do we need to access the variable as a function to get its value? 我如何知道用户何时与快速服务器断开连接 - How do I know when user disconnects with express server 当我尝试要求特定功能时,无法导出全局匿名对象 - Exporting a global anonymous object doesn't work when I try to require a specific function 当我需要一个文件夹但似乎不可能时,如何使用require安装SDK? - how do I install an SDK using require, when I need to require an folder and this seems impossible? Javascript -Node.js什么时候需要“需要”模块 - Javascript -Node.js When do i need to 'require' a module 我在我的节点 express 应用程序中发现此错误,它说 function 已将其命名为 sendMailer 不是 function。 这是我触发发送的时间 - am finding this error in my node express application its saying a function have named it sendMailer is not a function. this is when i trigger sent
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM