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

  • Ext JS 3.0 Cookbook
  • Jorge Ramon
  • 257字
  • 2021-04-01 13:43:45

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 = {};
主站蜘蛛池模板: 东辽县| 桂林市| 赤城县| 乐清市| 乌鲁木齐市| 北川| 宜阳县| 石泉县| 邮箱| 霍林郭勒市| 安义县| 巫山县| 庆城县| 门源| 札达县| 龙井市| 唐河县| 郸城县| 南部县| 新宁县| 惠来县| 茶陵县| 濮阳市| 日喀则市| 宜章县| 怀安县| 富民县| 平原县| 运城市| 工布江达县| 灵宝市| 方山县| 措勤县| 牡丹江市| 灌云县| 车致| 惠来县| 收藏| 宜春市| 庄浪县| 临桂县|