zoukankan      html  css  js  c++  java
  • Node.js入门学习笔记(二)

    函数传递

    举例来说,你可以这样做:

    function say(word) { 
        console.log(word); 

    function execute(someFunction, value) {
        someFunction(value); 

    execute(say, "Hello");

    请仔细阅读这段代码!在这里,我们把say函数作为execute函数的第一个变量进行了传递。这里返回的不是say的返回值,而是say本身!

    这样一来,say就变成了execute中的本地变量someFunction,execute可以通过调用someFunction()(带括号的形式)来使用say函数。

    当然,因为say有一个变量,execute在调用someFunction时可以传递这样一个变量。

    我们可以就像刚才那样,用它的函数名字把一个函数作为参数传递。但是我们不一定要绕这个‘先定义,再传递’的圈子,我们可以直接在另一个函数的括号中定义和传递这个函数。

    function execute(someFunction, value) {
        someFunction(value); 

    execute(function(word){console.log(word) }, "Hello");

    我们在execute接受第一个参数的地方直接定义了我们准备传递给execute的函数。用这种方式,我们甚至不用给这个函数起名字,这也是为什么它被叫做匿名函数。

    在Javascript中,一个函数可以作为另一个函数的一个参数,我们可以先定义一个函数,然后传递,也可以在传递参数的地方直接定义函数。

    函数传递是如何让HTTP服务器工作的

    带着这些知识,我们再来看看我们简约而不简单的HTTP服务器:

    var http = require("http"); 
    http.createServer(function(request, response) {
        response.writeHead(200, {"Content-Type": "text/plain"}); 
        response.write("Hello World"); response.end(); 
    }).listen(8888);

    现在它看上去应该清晰了很多:我们向 createServer 函数传递了一个匿名函数。

    用这样的代码也可以达到同样的目的:

    var http = require("http"); 
    function onRequest(request, response) { 
        response.writeHead(200, {"Content-Type": "text/plain"}); 
        response.write("Hello World"); 
    response.end(); } 
    http.createServer(onRequest).listen(8888);
  • 相关阅读:
    ORACLE-016:ora-01720 授权选项对于'xxxx'不存在
    leetcode笔记:Sort Colors
    指针常量与常量指针
    Tiling POJ 2506 【大数】
    杭电5137How Many Maos Does the Guanxi Worth
    ognl.OgnlException: target is null for setProperty(null,"XXXX"...)
    VM虚拟机全屏显示
    http://www.blogjava.net/crespochen/archive/2011/04/22/348819.html
    springMVC配置静态资源访问的<mvc:resources>标签的使用
    eclipse package explorer视图中怎么让default package不显示?
  • 原文地址:https://www.cnblogs.com/dzlishen/p/4488353.html
Copyright © 2011-2022 走看看