What is meant by 'JavaScript Namespacing'? [duplicate]

梦想的初衷 提交于 2019-12-03 03:10:31

问题


Possible Duplicate:
Javascript Namespacing

Im pretty new to JavaScript and was wondering if anyone could give me a good description of what is meant by JavaScript Namespacing?

Also any resources e.g. articles etc, are much appreciated on the subject.


回答1:


JavaScript is designed in such a way that it is very easy to create global variables that have the potential to interact in negative ways. The practice of namespacing is usually to create an object literal encapsulating your own functions and variables, so as not to collide with those created by other libraries:

var MyApplication = {
  var1: someval,
  var2: someval,
  myFunc: function() {
    // do stuff
  }
};

Then instead of calling myFunc() globally, it would always be called as:

MyApplication.myFunc();

Likewise, var1 always accessed as:

console.log(MyApplication.var1);

In this example, all of our application's code has been namespaced inside MyApplication. It is therefore far less likely that our variables will collide with those created by other libraries or created by the DOM.




回答2:


For a quick run down (including techniques), give this a read:

Namespacing in JavaScript




回答3:


I use this namespacing technique, along with "use strict" outlined by Crockford

var MyNamespace = (function () {
    "use strict"; 

    function SomeOtherFunction() {

    }

    function Page_Load() {

    }

    return { //Expose 
        Page_Load: Page_Load,
        SomeOtherFunction: SomeOtherFunction
    };
} ());

MyNamespace.Page_Load();



回答4:


Read up on a simple tutorial Here

Namespacing is used to avoid polluting the global namespace (no window. variables). In truth, each namespace is just a big variable, that has many properties and methods.

This happens, because in javascript you can have whole functions (methods) as variables



来源:https://stackoverflow.com/questions/8523231/what-is-meant-by-javascript-namespacing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!