nodejs功能提升:为什么它不起作用?

时间:2017-10-17 12:24:16

标签: node.js

这有效:

import Foundation

print("a".unicodeScalars.first!.value) // 97 
print("A".unicodeScalars.first!.value) // 65

let uppercase = String("abcde".flatMap { 
    guard let char = $0.unicodeScalars.first, 
          let uppercased = Unicode.Scalar(char.value - UInt32(97 - 65)) 
    else {
        return nil
    }
    return Character(uppercased)
})

print(uppercase) // ABCDE

但这不是

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

我不明白为什么因为它应该更多地提升我没有错误。

2 个答案:

答案 0 :(得分:6)

这不是函数提升,那是variable hoisting。它等同于:

 vm.dtOpt_product = DTOptionsBuilder.newOptions()
                .withOption('responsive', true)
        vm.dtOpt_product.withPaginationType('full_numbers');
        vm.dtOpt_product.withColumnFilter({
            aoColumns: [{
                    type: 'null'
                }, {
                    type: 'text',
                    bRegex: true,
                    bSmart: true
                }, {
                    type: 'text',
                    bRegex: true,
                    bSmart: true
                }, {
                    type: 'text',
                    bRegex: true,
                    bSmart: true
                }, {
                    type: 'select',
                    bRegex: false,
                    bSmart: true,
                    values: vm.dtProductTypes
                }]

        });

        vm.dtColDefs_product = [
            DTColumnDefBuilder.newColumnDef(0), DTColumnDefBuilder.newColumnDef(1),
            DTColumnDefBuilder.newColumnDef(2), DTColumnDefBuilder.newColumnDef(3).withClass('none'),
            DTColumnDefBuilder.newColumnDef(4), DTColumnDefBuilder.newColumnDef(5).notSortable()
        ];

函数提升仅适用于函数声明(上面是函数表达式):

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

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

答案 1 :(得分: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!');
}

在这种情况下,声明的函数尚不存在。