带要求的双参数: var io = require('socket.io')(http); [英] Double parameters with require: var io = require('socket.io')(http);
问题描述
我是 node 和 JS 的新手,正在研究 socket.io 聊天示例 (http://socket.io/get-started/chat/).我在服务器中遇到了这段代码:
I'm new to node and JS and was working thorough the socket.io chat example (http://socket.io/get-started/chat/). I came across this code in the server:
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
我看过其他教程,之前从未见过 require 后的双括号.(http)
部分有什么作用?是 require 的参数,是不是改变了类型,还是别的什么?
I've looked at other tutorials and never seen double parentheses after require before. What does the (http)
part do? Is it a parameter for require, doest it change the type, or something else?
谢谢!
推荐答案
在 JavaScript 中,函数是 一等公民.这意味着它可以被另一个函数返回.
In JavaScript, function is the First-class citizen. This means that it can be returned by another function.
考虑以下简单的例子来理解这一点:
Consider the following simple example to understand this:
var sum = function(a) {
return function(b) {
return a + b;
}
}
sum(3)(2); //5
//...or...
var func = sum(3);
func(2); //5
在您的示例中,require('socket.io')
返回另一个函数,该函数立即使用 http
对象作为参数调用.
In your example, require('socket.io')
returns another function, which is called immediately with http
object as a parameter.
这篇关于带要求的双参数: var io = require('socket.io')(http);的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!