0

I am currently writing all javascript functionality of a certain page in JQuery's document.ready handler:

$(document).ready(function() {
    var one, two, three;
    function f1(par1) {}
    function f2() {}
        ...
});

I feel that this isn't optimal or according to Javascript best practices. What I need is a private scope for the page's functionality, nothing needs to be called externally.

I've seen a number of different ways:

jQuery source

(function(window) { 
    var anObj = {};
    ... 
    window.functionality = anObj;
}(window));

A function that is self-invoked with the window as parameter, then setting the functionality object of your application on it.

Codemirror source

window.functionality = (function() {
   var functionality = {};
   ...
   return functionality;
}());

Very similar to what jQuery does, but setting the functionality object indirectly on window by making a self-invoking function return something first.

This question

var functionality = {};
(function(obj) { obj.f1 = ... }(functionality));

Creating a local variable (instead of on window), and setting its content inside a self-invoked function (why?)

How do I declare a namespace in JavaScript?

var functionality = { 
    f1: function(){}, 
    f2: function(){}
}

Pretty much the same as the previous thing but setting the contents without a self-invoking function (again why use or not use the self invoking function?).

So... which way is best?

4

1 回答 1

2

我会为此建议模块模式,其中页面被视为模块。网络上有很多关于 javascript 模块模式的信息。看看http://www.adequatelygood.com/JavaScript-Module-Pattern-In-Depth.html

我使用了链接中的一个示例并对其进行了一些修改:

var MyApp = MyApp || {};
MyApp.PageX = (function () {
    var my = {},
        privateVariable = 1;

    function privateMethod() {
        // ...
    }

    my.moduleProperty = 1;
    my.moduleMethod = function () {
        // ...
    };

    return my;
}());

这里发生的是,一组属性和方法被定义并命名为MyApp.PageXMyApp作为全局。所以这将起作用:

MyApp.PageX.moduleProperty; // 1
MyApp.PageX.moduleMethod();
于 2013-05-17T07:54:04.720 回答