简体   繁体   English

这两种要求在 Javascript 中有什么区别?

[英]What is the difference between these two kind of requiring in Javascript?

In a tutorial I saw a code like this:在一个教程中,我看到了这样的代码:

var session = require('express-session');
var FileStore = require('session-file-store')(session);

And another code like this:还有一个像这样的代码:

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

But I think I can write the first code like this:但我想我可以像这样编写第一个代码:

var sessionFileStore = require('session-file-store');
var FileStore = sessionFileStore.session;

And the second one like:第二个像:

var Schema = require('mongoose')(Schema);

OR或者

var Schema = require('mongoose').Schema;

I just wanted to ask for sure, are these two kind of writing equal or there are some differences?我只是想问一下,这两种写法是一样的还是有区别的?

I also like to know what is the meaning/difference if I use something like below for the second command:如果我对第二个命令使用如下所示的内容,我也想知道其含义/区别是什么:

var Schema = require('mongoose')('Schema');

It is the same.这是相同的。 require is a normal function, which returns a value. require是一个普通函数,它返回一个值。 So, if that value is also a function, you can immediately call it, or use one of its properties if it is an object.因此,如果该值也是一个函数,您可以立即调用它,或者如果它是一个对象,则使用其属性之一。

However, in the second case, require('mongoose')(Schema) will cause two errors:但是,在第二种情况下, require('mongoose')(Schema)会导致两个错误:

  1. Here require returns an object, not a function, so you can't invoke it.这里require返回一个对象,而不是一个函数,所以你不能调用它。
  2. You are using the variable Schema which has not been defined yet, and passing it as an argument to a function.您正在使用尚未定义的变量Schema ,并将其作为参数传递给函数。

In the second case, the right way to put it in a single line is var Schema = require('mongoose').Schema;在第二种情况下,将它放在一行中的正确方法是var Schema = require('mongoose').Schema;

And in the first case, I think that the correct way is var FileStore = sessionFileStore(session);在第一种情况下,我认为正确的方法是var FileStore = sessionFileStore(session); I assume here session is a global variable, or has been defined previously.我在这里假设session是一个全局变量,或者之前已经定义过。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM