我选择闭包而不是对象有实际原因吗?

发布于 2024-09-28 05:14:42 字数 1029 浏览 3 评论 0原文

我最近开始接触 OOP javascript,并且越来越多地听到有关闭包的信息。经过一天的绞尽脑汁,我现在理解了它们*,但我仍然没有看到相对于使用物体的优势。他们似乎做了同样的事情,但我怀疑我错过了一些东西。

*我想

编辑

我刚刚花了20分钟尝试使用一个作为对象编写的计数器和一个作为闭包编写的计数器来编写一个示例。我得出的结论是我仍然不明白闭包。

第二次编辑

好的,我已经成功地制作了一个极其简单的例子。这两者之间没有太多区别,但我发现对象版本更具可读性。为什么我会选择其中之一而不是另一个?


/*** Closure way ***/

function closureCounter() {
    var count = 0;
    return {
        increase : function() {
            count++;
            alert(count);
        },
        decrease : function () {
            count--;
            alert(count);
        }
    };
}

var myCounter = closureCounter();

myCounter.increase();
myCounter.decrease();


/*** Object way ***/

function objCounter() {
    var count = 0;
    this.increase = function() {
        count++;
        alert(count);
    }
    this.decrease = function() {
        count--;
        alert(count);
    }

}

var myCounter = new objCounter();

myCounter.increase();
myCounter.decrease();





I've been getting into OOP javascript recently and more and more I've been hearing about closures. After a day of twisting my brain I now understand them* but I still don't see the advantage over using an object. They appear to to do the same thing but I suspect I'm missing something.

*i think

Edit

I've just spent 20 minutes trying to write an example using a counter written as an object and a counter written as a closure. I have come to the conclusion that I still don't understand closures.

2nd Edit

Ok I've managed to whip of an extremely simple example. There isn't much between these two but I find the object version more readable. Why would I chose one over the other?


/*** Closure way ***/

function closureCounter() {
    var count = 0;
    return {
        increase : function() {
            count++;
            alert(count);
        },
        decrease : function () {
            count--;
            alert(count);
        }
    };
}

var myCounter = closureCounter();

myCounter.increase();
myCounter.decrease();


/*** Object way ***/

function objCounter() {
    var count = 0;
    this.increase = function() {
        count++;
        alert(count);
    }
    this.decrease = function() {
        count--;
        alert(count);
    }

}

var myCounter = new objCounter();

myCounter.increase();
myCounter.decrease();





如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

╰ゝ天使的微笑 2024-10-05 05:14:42

当闭包可以用更干净、更简单的代码做同样的事情时,您不必通过创建一个全新的对象来冒额外的错误和混乱的风险。使用闭包,链接对象变得更加容易。

举个例子:

function attachOnclick(eSource, eParent) {
    var e = document.createElement("div");
    eParent.appendChild(e);
    eSource.onclick = function() { e.style.backgroundColor = "881010"; }
}

如果

var elemLinks = [];
function attachOnclick2(eSource, eParent) {
    var e = document.createElement("div");
    eParent.appendChild(e);
    elemLinks.push({elemSrc: eSource, elemDest: e}); // Append to mappings list
    eSource.onclick = changeColor;
}

function changeColor() {
    for(var i = elemLinks.length; i--;) {
        if(this == elemLinks[i].elemSrc) { // We've found our match
            elemLinks[i].elemDest.style.backgroundColor = "881010";
            return true;
        }
    }

    return false;
}

您在第二个示例中发现任何错误,那么它就证明了我的观点,即闭包使编写简单、清晰的代码变得更加容易。

You don't have to risk additional bugs and confusion by creating a whole new object when a closure will do the same thing with cleaner and simpler code. With closures, it's much easier to link objects.

Case in point:

function attachOnclick(eSource, eParent) {
    var e = document.createElement("div");
    eParent.appendChild(e);
    eSource.onclick = function() { e.style.backgroundColor = "881010"; }
}

versus

var elemLinks = [];
function attachOnclick2(eSource, eParent) {
    var e = document.createElement("div");
    eParent.appendChild(e);
    elemLinks.push({elemSrc: eSource, elemDest: e}); // Append to mappings list
    eSource.onclick = changeColor;
}

function changeColor() {
    for(var i = elemLinks.length; i--;) {
        if(this == elemLinks[i].elemSrc) { // We've found our match
            elemLinks[i].elemDest.style.backgroundColor = "881010";
            return true;
        }
    }

    return false;
}

If you find any bugs in the second sample, then it just proves my point that closures make writing simple, cleaner code easier.

沉鱼一梦 2024-10-05 05:14:42

正如马斯特里克所说,你正在比较苹果和橙子。

对象只是键/值对的集合。闭包与变量作用域有关。您可以通过将代码的该部分包装在函数中来在任何情况下创建闭包。这会在该函数范围内创建一个新的闭包。

http://robertnyman.com/2008/10/09/解释-javascript-scope-and-closures/

两个对象创建示例之间的差异与在 JS 中编写类/对象的不同模式有关。我认为第一个例子称为模块模式?第二个示例是在 JS 中定义类的另一种常见方法,或者您也可以使用对象的原型来添加这些方法。

有关如何编写类的更多信息,请尝试谷歌搜索“js 类模式”(有很多资源,具有不同的模式 - 模块、显示模块、单例等)

Like masterik said, you're comparing apples and oranges.

An object is just a collection of key/value pairs. A closure relates to variable scoping. You can create a closure in any scenario, by wrapping that part of your code in a function. This creates a new closure within that function scope.

http://robertnyman.com/2008/10/09/explaining-javascript-scope-and-closures/

The difference between your two examples of object creation is related to different patterns of writing classes/objects in JS. The first example I believe is called the Module pattern? The second example is another common way of defining classes in JS, or you could also use the object's prototype to add those methods.

For more information on how to write classes, try googling "js class patterns" (there are quite a few resources, with different patterns - module, revealing module, singleton, etc)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文