公开闭包内部的方法 [英] Exposing a method which is inside a closure

查看:71
本文介绍了公开闭包内部的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我们在闭包内部创建方法时,该闭包将成为该闭包的私有属性,并且只有在以某种方式公开该闭包之后才能对其进行访问。

When we are creating a method inside a closure it becomes private to that closure and can't be accessed until we expose it in some way.

怎么做

推荐答案

您可以返回对其的引用...

You can return a reference to it...

var a = function() {

   var b = function() {
      // I'm private!
      alert('go away!');
   };

   return {
      b: b // Not anymore!
   };

};

在jsFiddle上查看

您还可以将其绑定到窗口对象。但是我更喜欢上面的方法,否则您将通过全局变量(它是 window 对象的属性)来公开它。

You could also bind it to the window object. But I prefer the method above, otherwise you are exposing it via a global variable (being a property of the window object).

这篇关于公开闭包内部的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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