什么可以使用javascript闭包? [英] What can javascript closures be used for?

查看:129
本文介绍了什么可以使用javascript闭包?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在想一会儿 - 什么可以使用JavaScript闭包?



我知道如何写它们,我知道它们如何工作,但我只是不能得到如何使用的想法。

  function closure(){
var name = 约翰;
function displayName(){
return'Hello,'+ name;
}
return displayName;
}

到目前为止,我只找到一个用途 - 封装数据,在函数外部是可见的。



但是还可以使用什么呢?我应该用闭包写OOP吗?我需要把所有的代码放在一个闭包,所以它不会混乱全局范围?



任何澄清都非常感激!



<$ p $

p> function Singleton(){
//缓存实例
var instance = this;

//正常进行 - 添加一些变量
this.variable1 = 1000;
this.variable2 = 3000000;

Singleton = function(){
return instance;
}
}

var singleton1 = new Singleton();
var singleton2 = new Singleton();

if(singleton1 === singleton2){
console.log(Singleton works :));
}
else {
console.log(Singleton does not work:/);
}

您可以直接将此代码粘贴到Chrome JavaScript控制台。



当然你可以调整它以适应你的需要。还有一些缺点 - 你可以覆盖Singleton函数,你将不能再访问实例了。但这是另一个问题。



我发现它很久以前在JavaScript模式书由Stoyan Stefanov(O'Reilly)
。检查这一点,因为有其他有用的设计模式和关闭应用程序的示例。根据这本书:

 你可以使用closure来存储一些私有数据,可以通过返回的函数访问,但不能访问外部代码。 


I've been wondering for a while - what can JavaScript closures be used for?

I know how to write them and I know how they work, but I just can't get the idea of how they can be used.

function closure() {
  var name = "John";
  function displayName() {
    return 'Hello, ' + name;
  }
  return displayName;
}

So far I only found one use for them - encapsulating data, so it won't be visible outside the function.

But what else can they be used for? Should I write OOP with closures? Do I need to put all my code inside a closure so it wont mess the global scope?

Any clarifications are highly appreciated!

解决方案

Personally, besides obvious things like encapsulating or creating private contexts, I like Singleton JavaScript Design Pattern:

function Singleton() {
    // cached instance
    var instance = this;

    //proceed as normal - adding some variables
    this.variable1 = 1000;
    this.variable2 = 3000000;

    Singleton = function() {
        return instance;
    }
}

var singleton1 = new Singleton();
var singleton2 = new Singleton();

if(singleton1 === singleton2) {
    console.log("Singleton works :)");
}
else {
    console.log("Singleton doesn't work :/");
}

You can paste this code directly into Chrome JavaScript console.

Of course you can tweak it to suit your needs. There is also some drawback - you can overwrite Singleton function, and you will not be able to access instance anymore. But this is another problem.

I found it a long time ago in JavaScript Patterns book by Stoyan Stefanov (O'Reilly) . Check this out as there are other useful design patterns and examples of closures application. According to this book:

You can use closure to store some private data, which is accessible by the returned function but not to the outside code.

这篇关于什么可以使用javascript闭包?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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