在自执行方法中访问Javascript作用域

Javascript scope access in self-executing method

本文关键字:访问 Javascript 作用域 方法 执行      更新时间:2023-09-26

我在定义模块模式时遇到了一个问题(http://robots.thoughtbot.com/module-pattern-in-javascript-and-coffeescript):

)

下面这段代码正常工作(CoffeeScript):

window.Map = {}
Map.handle = ( ->
  handle = 'some text'
  print: () ->
    console.log handle    
)()

现在,如果我将'some text'替换为全局范围内可用的库中的方法(即gmaps4rails: https://github.com/apneadiving/Google-Maps-for-Rails):

)
window.Map = {}
Map.handle = ( ->
  handle = Gmaps.build('Google')
  print: () ->
    console.log handle    
)()

代码不工作并抛出Map.handle未定义。所以我认为这是一个范围的问题,所以我尝试传递Gmaps.build('Google')作为一个参数到匿名函数,但它失败了。

Gmaps。

window.Map = {}
Map.handle = ( ->
  mapBuildFx = () ->
    handle = Gmaps.build('Google')
)()

工作正常

我到底错过了什么?

当我尝试任何版本的代码时,我获得ReferenceError: Map is not defined

我不知道这是否真的是你的问题,但至少,你忘记将Map限定为window.Map:

window.Map = {}
window.Map.handle = ( ->
  handle = Gmaps.build('Google')
  print: () ->
    console.log handle    
)()
# Use `print` like that:
do window.Map.handle.print
# or
window.Map.handle.print()

未使用Gmaps进行测试


先不考虑其他一些小错误和/或Gmap特性(?),并回答题目为:Javascript在自执行方法:

中的作用域访问

在该片段中,handle是匿名函数的本地值。因此,它在其定义中的任何地方都是可见的——甚至在子函数中也是如此。但是,除非你让它以某种方式逃脱,否则它将从外部隐藏起来:

coffee> console.log window.Map.handle
{ print: [Function] }

顺便说一句,您可以在函数定义中使用do ->而不是不太习惯的( -> ...)()