简体   繁体   中英

nodejs function hoisting : why it doesn't work?

This works:

    var http = require('http');

    var handler = function (req, res) {
        res.writeHead(200, {'Content-Type': 'text/plain'});
        res.end('Hello World!');
    }


    http.createServer(handler).listen(8080);

But this doesn't

    var http = require('http');

    http.createServer(handler).listen(8080);

    var handler = function (req, res) {
        res.writeHead(200, {'Content-Type': 'text/plain'});
        res.end('Hello World!');
    }

I don't understand why since it should with hoisting all the more I got no error.

That's not function hoisting, that's variable hoisting . It's equivalent to this:

var http = require('http');
var handler;

http.createServer(handler).listen(8080);

handler = function (req, res) {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end('Hello World!');
}

Function hoisting works only for function declarations (the above is a function expression ):

var http = require('http');

http.createServer(handler).listen(8080);

function handler(req, res) {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end('Hello World!');
}

More info: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function#Function_declaration_hoisting

var http = require('http');

http.createServer(handler).listen(8080);

var handler = function (req, res) {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end('Hello World!');
}

In this case the declared function does not yet exist.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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