这可能是完全显而易见的,但我想确认允许通过createServer方法内的匿名或命名函数访问请求和响应对象的“机制”是闭包的示例吗?那是createServer是外部函数,而其他返回函数是内部函数,可以访问请求和响应对象?
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World\n');
}).listen(1337, '127.0.0.1');
console.log('Server running at http://127.0.0.1:1337/');
不,它们只是简单的方法参数。这是我的标准“超级清晰的封闭示例”代码段:
var tipper = function (percentage) {
return function tip(total) {
return total + (total * (percentage / 100));
};
};
var generous = tipper(20);
var normal = tipper(18);
var stingy = tipper(8);
console.log(generous(24.50), normal(24.50), stingy(24.50));
内部tip
函数对percentage
变量的持久访问,即使在外部tipper
函数返回后也是如此。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句