编写将所有内容都包含在变量中的Javascript代码

Writing Javascript code having everything in a variable

本文关键字:变量 代码 Javascript 包含      更新时间:2023-09-26

我早些时候从我正在查看的PhoneGap/cordova文件中了解到了这一点:

  var app = {
    initialize: function() {
        this.bind();
    },
    bind: function() {
        document.addEventListener('deviceready', this.deviceready, false);
    },
    deviceready: function() {
        // This is an event handler function, which means the scope is the event.
        // So, we must explicitly called `app.report()` instead of `this.report()`.
        app.report('deviceready');
        app.handleLogin();
    },
  }

我只是想知道,与在主体负载上执行的独立函数相比,这样做有什么好处?此外,如果我要在jquery mobile中的"pagebeforeload"上运行一个函数,我将如何将其集成到上述模式中?例如:

    $( '#mainMenu' ).live( 'pagebeforeshow', function(event){
    alert('pagebeforeshow');
});

简而言之,就是名称空间。

在JavaScript中,一切都是全局的,除非您明确地使其不全局。这意味着事物的名称可能会发生冲突,或者你可以覆盖你不想覆盖的东西。这在大型程序中是个大问题。

显示的模式将应用程序的所有功能命名为单个app"对象"。因此,任何在全局范围内覆盖bind的操作都不会影响app.bind的值。命名空间保护它。

一个好的经验法则是尽可能少地污染全局命名空间。在这种情况下,您将app设为全局值,仅此而已。您的所有代码都挂起这一全局值。整洁。


至于如何整合你的例子。我可能会这样做:

  var app = {
    initialize: function() {
        app.bindEventHandlers();
        // other setup code called here...
    },
    bindEventHandlers: function() {
        $( '#mainMenu' ).live( 'pagebeforeshow', app.pageBeforeShow );
        // other event handlers bound here...
    },
    pageBeforeShow: function() {
        alert('pagebeforeshow');
    },
    // other event handler functions declared here...
    // or whatever other functions or data your app needs here...
  }
  // start your app when the document is ready
  $(document).ready(function() {
    app.initialize();
  });

若您使用OOP语言,那个么您就知道类的定义。JS不支持class关键字,所以要用方法创建对象,应该使用以下代码。然后你可以调用app.initialize()。它还可以为你的应用程序的体系结构提供高级功能。

要将代码集成到现有功能中,您应该创建原型。

app.prototype = { nameOfFunctionHere: function() { alert('pagebeforeshow'); } }

然后打电话给

app.nameOfFunctionHere();

执行您的功能