簡體   English   中英

無法讀取CoffeeScript全局變量

[英]Can't read CoffeeScript global variable

我有兩個coffeescript文件,第一個有以下幾行:

jQuery(document).ready ($) ->
   dispatcher.bind "createuserchannel", (channelid) ->
     root = (exports ? this)
     root.channel_user = dispatcher.subscribe(channelid)

后者是:

jQuery(document).ready ($) ->
 root = (exports ? this)
 console.log root.channel_user

我不知道為什么,但是在Chrome控制台中,當我編寫Object.keys(window)channel_user顯示為全局變量,但是如果我嘗試從Javascript訪問它,則只會得到未定義

在jQuery事件的回調(例如第二種情況)中,jQuery this設置為觸發事件的對象(在本例中為document )。 您看到兩個選擇:

首先,您可以顯式使用window 目前尚不清楚這是否適合您的用例。

root = (exports ? window)

其次,您可以使用CoffeeScript粗箭頭從外部范圍保留this箭頭。 請注意,如果您在該函數中的其他任何地方都依賴this行為,則會造成麻煩。

jQuery(document).ready ($) =>

我想在第二種情況下也會發生同樣的情況,但是如果不確切知道dispatcher是什么,就不可能確定。

解決了:

dispatcher.bind是一個異步函數,因此在我從該函數訪問變量時:

jQuery(document).ready ($) ->
 root = (exports ? this)
 console.log root.channel_user

channel_user仍未分配。 為了解決該問題,我添加了以下行:

jQuery(document).ready ($) ->
     dispatcher.bind "createuserchannel", () ->
      root = (exports ? this)
      console.log root.channel_user

這樣,僅當設置了channel_user時,才會調用root.channel_user

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM