公开闭包内的方法
当我们在闭包中创建一个方法时,它就成为该闭包的私有方法,并且在我们以某种方式公开它之前无法访问它。
怎么可能暴露呢?
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.
How can it be exposed?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以返回对它的引用...
在 jsFiddle 上查看。
您还可以将其绑定到
window
对象。但我更喜欢上面的方法,否则您将通过全局变量(作为window
对象的属性)公开它。You can return a reference to it...
See it on jsFiddle.
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 thewindow
object).您需要以某种方式将其传递到外部。
示例: http://jsfiddle.net/patrick_dw/T9vnn/1/< /a>
You need to pass it to the outside in some manner.
Example: http://jsfiddle.net/patrick_dw/T9vnn/1/
您可以通过在 this 作用域(可以根据调用而改变)中内部声明闭包的函数或属性来公开它们。
this 中声明的方法可以访问使用 var 声明的变量,但反之则不行。
函数在范围内关闭。您想要做的是返回对有权访问所需范围的函数的引用,以便您可以在以后调用它。
如果您需要创建一个在稍后调用特定方法的函数,
如果作用域是一个问题,
您可以使用不太可读的示例内联大部分内容,
setTimeout 只是一种方便的方法展示新范围内的执行力。
You expose functions or properties of a closure by internally declaring them in this scope (which can change depending on invocation).
Methods declared in this can access variables declared using var, but not the other way 'round.
The function closes over the scope. What you want to do is to return a reference to a function that has access to the scope you require so you can invoke it at a later point.
If you need to create a function that calls a specific method at some later point,
If scoping is an issue,
You can inline most of this with the less readable example of,
setTimeout is just a convenient way of demonstrating execution in new scope.
出于性能目的,您可以通过以下方式调用它:
For performance purposes you can invoke it this way: