2017-10-17 85 views
0

這工作:nodejs函數提升:爲什麼它不起作用?

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); 

但這並不

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!'); 
    } 

我不明白爲什麼,因爲它應與吊裝更加我沒有錯誤。

+0

因爲你的天堂」 t定義處理程序了嗎?當它是一個對象時,它只通過引用傳遞變量 – lumio

+0

@ lumio通常允許在之後定義var,這樣我的問題。 – user310291

+0

吊裝只適用於函數聲明而不適用於函數表達式:https://stackoverflow.com/q/336859/1169798 – Sirko

回答

4

這不是功能提升,那是variable hoisting。這是相同的:

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!'); 
} 

功能提升僅適用於功能聲明(上面是一個功能表達):

var http = require('http'); 

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

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

更多信息:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function#Function_declaration_hoisting

1

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!'); 
} 

在這種情況下,聲明的函數還不存在。

相關問題