【问题标题】:Javascript scope access in self-executing method自执行方法中的 Javascript 范围访问
【发布时间】:2014-08-17 23:16:49
【问题描述】:

在定义模块模式时,我对一个问题感到很困惑 (http://robots.thoughtbot.com/module-pattern-in-javascript-and-coffeescript):

以下代码可以作为 exepted (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.build 自做以来就可以正常工作:

window.Map = {}

Map.handle = ( ->

  mapBuildFx = () ->
    handle = Gmaps.build('Google')
)()

按预期工作。

我到底错过了什么?

【问题讨论】:

  • AFAIK,没有理由从给定的代码中抛出Map.handle is undefined。你如何使用你的“单例”对象?

标签: javascript ruby-on-rails coffeescript gmaps4rails


【解决方案1】:

当我尝试任何版本的代码时,我都会获得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()

未经 Gmap 测试


撇开其他一些小错误和/或 Gmap 特性 (?),并回答标题为:Javascript scope access in self-executing method

在该片段中,handle 对于匿名函数是本地的。所以它在其定义内的任何地方都是可见的——甚至在子功能中也是如此。但除非你让它以某种方式逃跑,否则它将被隐藏起来:

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

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

【讨论】:

  • 是的,我只是没有在此处粘贴该行,让我更新一下:)
猜你喜欢
  • 1970-01-01
  • 2021-12-04
  • 1970-01-01
  • 1970-01-01
  • 2016-03-04
  • 2017-03-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多