3

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');

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

4

1 回答 1

8

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

有了var您可以访问lists文件中的任何位置。

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

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

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

于 2013-07-22T13:06:24.817 回答