【问题标题】:Defining variable in Meteor.js在 Meteor.js 中定义变量
【发布时间】:2013-07-22 13:04:36
【问题描述】:

当我如下定义变量lists并在控制台中输入lists时,我得到错误ReferenceError: lists is not defined

var lists = new Meteor.Collection('Lists');

if (Meteor.isClient) {
  Template.hello.greeting = function () {
    return "my list.";
  };

  Template.hello.events({
    'click input' : function () {
      // template data, if any, is available in 'this'
      if (typeof console !== 'undefined')
        console.log("You pressed the button");
    }
  });
}

if (Meteor.isServer) {
  Meteor.startup(function () {
    // code to run on server at startup
  });
}

仅当我将lists 声明为全局变量时才有效:

lists = new Meteor.Collection('Lists');

问题:为什么它必须是全局范围的?

【问题讨论】:

标签: javascript meteor


【解决方案1】:

要在控制台中访问lists,您需要使用全局范围,因为控制台超出了文件本身的范围,因为控制台被视为自己的文件。

使用var,您可以在文件中的任何位置访问lists

本质上,每个文件都包含在function() {..} 中。这就是为什么每个文件的变量都不能在它们之外访问的原因。

变量作用域存在的原因稍微复杂一些,但更多地与第三方包/npm 模块有关。每个包都需要有自己的范围,不会与外部的东西发生名称冲突。

如果您希望能够更正常地使用它,您也可以将它放在/compatibility 文件夹中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-12-07
    • 1970-01-01
    • 2013-07-23
    • 2014-01-15
    • 2013-12-06
    • 2011-09-27
    • 2019-11-11
    • 2019-04-18
    相关资源
    最近更新 更多