关于使用实际关闭的疑问 [英] Doubts About Use of Practical Closure

查看:90
本文介绍了关于使用实际关闭的疑问的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在Javascript中了解更多关于closures的信息,并正在执行此操作: https://developer.mozilla.org/en/JavaScript/Guide/Closures#Tractical_closures

I'm trying to find out more about closures in Javascript and was going through this: https://developer.mozilla.org/en/JavaScript/Guide/Closures#Practical_closures

根据本文,通过使用此类函数:

According to this article, by using such a function:

function makeSizer(size) {  
    return function() {  
        document.body.style.fontSize = size + 'px';  
    };  
}  

var size12 = makeSizer(12);  
var size14 = makeSizer(14);  
var size16 = makeSizer(16); 

然后我们可以使用这样的语句来增加/减少一个页面上的文本的字体大小:

We can then make use of such statements to increase/decrease the font-size of text on a page:

document.getElementById('size-12').onclick = size12;  
document.getElementById('size-14').onclick = size14; 
document.getElementById('size-16').onclick = size16;

虽然我理解这里的概念 - 即size12,size14和size16成为闭包,允许访问内部功能,我不禁感到这是不必要的。是不是更容易只有:

While I understand the concept here - i.e. size12, size14 and size16 become closures that allow access to the internal function, I can't help but feel that this is unnecessary. Isn't it easier to just have:

function makeSizer(size) {  
    document.body.style.fontSize = size + 'px';  
}   

,然后使用这些命令调用它们?

, and then invoke it with these?

document.getElementById('size-12').onclick = makeSizer(12);  
document.getElementById('size-14').onclick = makeSizer(14); 
document.getElementById('size-16').onclick = makeSizer(16);

任何人都可以告诉我,如果我的想法是正确的 - 也许我只是一个新手Javascript和不理解在这种情况下使用闭包的优势,在这种情况下,如果你能解释这样做的优点,我会非常高兴。

Can anyone tell me if my thinking is right - or maybe I'm just a novice to Javascript and doesn't understand the advantage to using closure in this scenario, in which case I'll be most glad if you can explain the advantage of doing so.

提前感谢

推荐答案

对于您提供的示例,当然不需要关闭,但我想这只是为了简单提出的概念。有些情况下,闭包是最好的解决方案使用:考虑如何实现一个私有属性在javascript或当你需要

For the example you presented, of course closure is not necessary, but I guess it is just to make it simple to present the concept. There are cases though that closure is the best solution to use: think about how to implement a "private" attribute in javascript or when you need curryng to encapsulate arguments (ie, for a callback function).

我希望以下示例有助于:

I hope the following example helps:

var makeSequencer = function() {
    var _count = 0; // not accessible outside this function
    var sequencer = function () {
        return _count++;
    }
    return sequencer;
}

var fnext = makeSequencer();
var v0 = fnext();     // v0 = 0;
var v1 = fnext();     // v1 = 1;
var vz = fnext._count // vz = undefined

这篇关于关于使用实际关闭的疑问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆