开发者

Javascript Namespacing

开发者 https://www.devze.com 2023-04-11 04:00 出处:网络
I wish to make my javascript more more modular by splitting it up into different files and giving each file a \'sub\' namespace like so.

I wish to make my javascript more more modular by splitting it up into different files and giving each file a 'sub' namespace like so.

subA.js

if(typeof ex == "undefined") {
    var ex = {};
}

ex.subA = function() {
//all functions of subA here
}

And same for subB etc.

At the moment I have 1 file, ex.js

var ex = (function() {
    //private vars/funcs
    return {
        //public vars/funcs
    }
})();

It looks like I should move most of my functions to subA.js and subB.js but still include ex.js at the start, with subA.js and subB.js afterwards.

I have a number of questions.

  1. I'm having a hard time remembering how I made the initial namespacing file, ex.js. It looks like the anonymous function is there to make everything private initially, but I can't remember why it needs to be enclosed in parentheses and then executed straight away with the (); at the end.

  2. Following on from q1, should my sub files be in the same format as ex.js, ie, have the anon function wrapped in parentheses and executed straight away?

  3. It looks like the sub files will only have access to the public functions of ex, is this true? If it is, how can I allow my sub files access to the private functions as well?

  4. In my HTML file, in my document.ready function (jQuery), should I be initialising ex to a variable or can I call each function individually by going

$(document).ready(function() {
    ex.doSomething();
    ex.doSomethingElse();
}

Is there a difference between the two? I think that when ex.js is included, a global variable ex is created straight away (due to the anonymous function being executed straight away), so I shouldn't need to redefine it in document.ready.

  1. Is the first if statement in subA.js any different from var ex = ex || {}; Which is better?

  2. What js code style standards do you use?

If you read through all this you already deserve an upvote开发者_开发知识库, cheers.


1. The function(){ return{}} is a closure to add "privacy" to the variables and functions you don't want to be accessible anywhere else but within the scope of that function. The parentheses around the function (function(){}) create a function expression. They are used, because the parser will complain when you try to execute a function immediately function(){}() without passing any argument to ().

2. If you want subA or any other extending object to have its own subfunctions, then yes, you have to declare it like that, but not neccesarly a clousure though.

You can do

ex.subA = function(x, y){
    return x+y;
}

which can be called var sum = ex.subA(2, 3);

Or you can do

ex.subA = (function(){

    return {
        add: function(x, y){
            return x+y;
        },
        multiply: function(x, y){
            return x*y;
        }
    }
})();

Then call it var sum = ex.subA.add(2, 3); var multiplication = ex.subA.multiply(2,3);

There are many ways to do this.

3. Yes, it is true. You can make the private functions public. The closure won't allow any other way to do it.

4. If you would like to alias, yes you can assign it to a variable. However, there is no need to. It will work fine the way you are describing it.

Read Essential JavaScript Namespacing Patterns to understand some fundamentals and patterns in javascript namespacing.


Is the first if statement in subA.js any different from var ex = ex || {}; Which is better?

First of, the if statement should be if(typeof ex == 'undefined'), the typeof returns a string. There isn't any need to check if ex is false.

Yes, it is different. The if statement will not do any variable assignment if the variable ex is already defined. Therefore, the if statement is better.

What js code style standards do you use?

Depends on the scope of the project, but mostly deep object extending with a helper function.


In you design, you won't have access to private vars/funcs define in that lambda function, because it only return a object, or you want to use new?

1.Without the (), ex is a function not the object the functions returns.

2.no need, except you want to pass some parameters for initialization. e.g.

ex.my = (function(name) {var my_name = name;})('bar');

3.I think you mean this private method.

ex = (function() {
    var foo = 'bar';
    return {
        show: function() {alert(foo);}
    }
})();

In the case above, only ex can access foo.

4.no need, $(document).ready() is called when everything is ready, if you already loaded ex.js, the initialization is done.

Everything inside it will load as soon as the DOM is loaded and before the page contents are loaded


For Questions 1 and 3:

A closure style defenition in the ex.js will allow those public functions and vars/exposed.

My thought is, it is better to return "ex" from the anomyous function with the functions and vars we need to expose.

for Q3. Those ( private )variables defined and used in returned function is still avaialble to the function and can be used through the exposed function ( property of closure ).

If the external script include is in the section or at the top of the file, the ex should be available before document.ready and should be usable straight away.

You are making me think :) Will update the post as I dig further in to this. Very good Questions. :)

0

精彩评论

暂无评论...
验证码 换一张
取 消