【问题标题】:browser returns an error: app is not defined浏览器返回错误:应用未定义
【发布时间】:2017-07-15 17:11:57
【问题描述】:

我有一个应用程序在前端的 Backbone 上运行,当浏览器加载页面时,它会在控制台中返回错误:

Uncaught ReferenceError: app is not defined
    at index.js:6
    at index.js:51
(anonymous) @ index.js:6
(anonymous) @ index.js:51

index.js

/* global app:true */

(function() {
  'use strict';

  app = app || {};  // error here although it must prevent of undefined 
                    // variables stay undefined

  //.......
  //backbone code here
  //.......

  $(document).ready(function() {
    app.contactView = new app.ContactView(); //error here
  });
}());

从构建切换到 CDN 或进入 Backbone.Model 属性返回相同的错误。

【问题讨论】:

    标签: javascript namespaces javascript-namespaces


    【解决方案1】:

    如果您希望它是全局的,则仅将变量移到函数范围之外。

    /* global app:true */
    
    var app = app || {};
    
    (function() {
      'use strict';
    
      //.......
      //backbone code here
      //.......
    
      // you can use the jQuery shortcut version of the document ready.
      $(function() {
        app.contactView = new app.ContactView();
      });
    }());
    

    或者将其作为IIFE的参数传递。

    (function(app) {
      // ...
    })(app = app || {});
    

    如果您有多个文件,它们都应该实现与上述示例类似的结构,以便能够使用 app 命名空间。

    有关命名空间的其他信息

    【讨论】:

    • 不,这两个选项返回相同的错误。我还有一些结构相似的文件,也许我应该更改它们,否则它不会是全局的?
    • @ASem 每个文件的顶部都应该有var app = app || {}; 行。
    • 把它们都改了,有帮助,谢谢!据我了解,您的第一个选项使全局应用程序对象可访问,但其属性位于函数范围内,这样离开是安全的。
    • @ASem 实际上,app 中的所有内容都可以全局访问,因为app 是一个全局变量。函数作用域允许您定义不会泄漏到全局空间的局部变量。这对于组件的私有部分、模拟 class 的静态字段等很有用。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-25
    相关资源
    最近更新 更多