在Meteor.js中定义变量

Nyx*_*nyx 3 javascript meteor

当我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
  });
}
Run Code Online (Sandbox Code Playgroud)

它只有在我声明lists为全局变量时才有效:

lists = new Meteor.Collection('Lists');
Run Code Online (Sandbox Code Playgroud)

问题:为什么必须全球化?

Aks*_*hat 8

lists在控制台中访问,您需要使用全局范围,因为控制台不在文件范围内,因为控制台被视为自己的文件.

随着var您可以访问lists该文件的任何地方.

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

存在变量范围的原因稍微复杂一些,但与第三方软件包/ npm模块更相关.每个包都需要有自己的范围,不会与外面的东西发生名称冲突.

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