简体   繁体   English

'variable':function(req,res){}是什么意思?

[英]'variable' : function(req, res){} means?

I am currently starting with node.js, so I am for the first time using Js beyond dom manipulation. 我目前从node.js开始,所以我第一次使用Js来进行dom操作。

I came across a code piece like below. 我遇到了如下代码。 I cant understand it. 我听不懂。 What is happening? 怎么了? is it a key value object? 它是键值对象吗? Is an anonymous function being passed to 'new' ? 是否将匿名function传递给'new'

module.exports = {

  'new': function(req, res) {
    res.view();
  },

  /**
   * Overrides for the settings in `config/controllers.js`
   * (specific to UserController)
   */
  _config: {}


};

As others have said, this is ultimately just creating an object called module.exports then assigning two properties to it. 正如其他人所说,这最终只是创建一个名为module.exports的对象,然后module.exports分配两个属性。 One is another object called _config and the other is a function called new that expects two arguments. 一个是另一个名为_config对象,另一个是一个名为new的函数,该函数需要两个参数。

That's the plain JavaScript explanation. 这就是普通的JavaScript解释。

In node.js, you're also seeing a few conventions in play, which I'll describe below. 在node.js中,您还可以看到一些约定,下面将对此进行描述。


One convention is module.exports . 一种约定是module.exports

This is the object that will be made available when some other code loads this file using require() . 当其他一些代码使用require()加载此文件时,将使该对象可用。 It would work something like this: 它会像这样工作:

var m = require('yourmodule.js');
m.new(req, res);

Another convention is the pair of arguments: req, res . 另一个约定是一对参数: req, res

These are usually parameters that represent a request (like an http.IncomingMessage ) and a response (like a http.ServerResponse ). 这些通常是代表请求(例如http.IncomingMessage )和响应(例如http.ServerResponse )的参数。


Putting it all together, this module is probably defining a Controller that will receive http requests, and render them as responses. 综上所述,此模块可能定义了一个控制器,该控制器将接收http请求并将其呈现为响应。 It currently does this for new , and there are probably routes configured elsewhere that call this method when a user requests something like ' http://server.come/user/new '. 当前,它是对new执行此操作的,当用户请求诸如“ http://server.come/user/new ”之类的内容时,可能在其他地方配置了调用此方法的路由。

Looks like basic JavaScript. 看起来像基本的JavaScript。

An object named module has a property named exports that is an object. 名为模块的对象具有名为exports的属性,该属性是一个对象。

This object has a property named new whose value is an anonymous function. 该对象具有一个名为new的属性,其值为匿名函数。

In theory you could invoke the method like this: 从理论上讲,您可以调用如下方法:

module.exports.new(someRequest, someResponse);

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

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