官术网_书友最值得收藏!

Preventing naming conflicts and scoping non-global variables

Naming conflicts and scoping problems increase as applications gain size, and you start to work with multiple code files and modules. In Ext JS, you can resolve these issues by creating namespaces where you can logically organize your code.

How to do it...

The following steps will show how to create a namespace and "hide" local variables in it. These variables will not collide with similarly-named variables that are stored in other namespaces or have global scope:

  1. Define a namespace for the variables that are not global:
    Ext.namespace('ExtJSCookbook.Samples');
    
  2. Create a local variable and a global variable with the same name:
    Ext JSCookbook.Samples.var1 = 'var1 (local)';
    // ExtJSCookbook.Samples.var1 is limited to the ExtJSCookbook.Samples namespace
    var var1 = 'var1 (global)';
    // var1 is a global variable
    
  3. Prevent name collisions by putting any custom types inside the namespace you created:
    // A custom type inside the Ext JSCookbook.Samples namespace
    ExtJSCookbook.Samples.Person = function() {
    return {
    firstName: '',
    lastName: '',
    show: function() {
    alert(this.firstName + ' ' + this.lastName);
    }
    }
    }
    var person1 = new Ext JSCookbook.Samples.Person();
    person1.firstName = 'Jorge';
    person1.lastName = 'Ramon';
    person1.show();
    

How it works...

Ext.namespace(namespace1, namespace2, namespace3,...) and its shorthand Ext.ns(...) allow you to create an arbitrary number of namespaces that you can use to scope variables and classes that are not global. For example, have a look at the following piece of code:

Ext.namespace('MyApplication', 'MyApplication.UI', 'MyApplication.Data', 'MyApplication.Services');

This namespace's definition above is equivalent to the following statements:

MyApplication = {};
MyApplication.UI = {};
MyApplication.Data = {};
MyApplication.Services = {};
主站蜘蛛池模板: 正宁县| 东至县| 临湘市| 桂东县| 大洼县| 平遥县| 灵武市| 邯郸市| 怀安县| 黑河市| 吴江市| 万安县| 建湖县| 垣曲县| 沁阳市| 噶尔县| 延边| 东丽区| 浙江省| 灯塔市| 大竹县| 扎鲁特旗| 绥德县| 罗城| 咸宁市| 汕头市| 固安县| 潜江市| 乐至县| 江源县| 南城县| 托克逊县| 崇明县| 武陟县| 望江县| 平凉市| 昆山市| 冀州市| 鹤岗市| 南皮县| 临潭县|