javascript - NodeJS connect module use problem
漂亮男人
漂亮男人 2017-07-03 11:42:55
0
1
914

I am new to nodejs. There is such a piece of code in the amazing NodeJS. Through middleware, the console printing of the code request time is too long

//request-time.js
module.exports = function(opts){
    var time = opts.time||100;
    return function(req,res,next){
        var timer = setTimeout(function(){
            console.log(req.method + " , " + req.url + " , too long!");
        },time);

        var end = res.end;
        res.end = function(chunk,encoding){
            res.end = end;                                        //
            res.end(chunk,encoding);                        //直接end(chunk,encoding)会出错
            clearTimeout(timer);
        };
        next(); 
    }
}

The comment part is my question. I guess there is something about this in the end. I don’t know if I understand it correctly.

漂亮男人
漂亮男人

reply all(1)
phpcn_u1582

The term "closure" comes from the combination of a block of code to be executed (because the free variables are contained within the block, these free variables and the objects they refer to are not released) and the binding provided for the free variables. Computing environment (scope) ---Baidu Encyclopedia

Let’s talk about the concept of closure first

Your understanding is correct
,
This is the verification process, the reason is because if you call end directly, this end is forcibly left because of this closure, so it will be automatically bound to the computer environment, so this is the later Its this is Window, so calling end directly will cause an error

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!