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

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

Extending JavaScript objects, the Ext JS way

You can use Ext JS to enhance the native JavaScript classes by making your own functions appear as if they were members of these classes. This recipe uses the Array class as an example, explaining how to augment its features by adding a function that will allow an array to copy itself into another array.

How to do it...

Adding a new function to the Array class is shown in the following steps:

  1. Use Ext JS to add a new function, copyTo(array, startIndex), to the Array class's prototype:
    Ext.applyIf(Array.prototype, {
    copyTo: function(dest, startIndex) {
    l = this.length;
    for (var i = 0; i < l; i++) {
    dest[startIndex + i] = this[i];
    }
    }
    })
    
  2. Create a source array and a destination array in order to test the new function:
    var source = new Array();
    var destination = new Array();
    source[0] = '1';
    source[1] = '2';
    source[2] = '3';
    destination[0] = '4';
    destination[1] = '5';
    destination[2] = '6';
    destination[3] = '7';
    destination[4] = '8';
    destination[5] = '9';
    
  3. Verify that the function is available in the Array class:
    var serialized = destination.toString();
    // serialized is "4,5,6,7,8,9"
    // Copy the source array, starting at index 2 of the destination
    source.copyTo(destination, 2);
    serialized = destination.toString();
    // serialized is "4,5,1,2,3,9"
    
    

How it works...

Ext.applyIf(object1, object2) copies all of the properties of object2 to object1, if they do not already exist. This effectively allows you to add new functionality to object1.

There's more...

If you want to add or replace an object's current properties, you can use Ext.apply(object1, object2). This function will copy the properties of object2 to object1, replacing the ones that object1 has already defined.

主站蜘蛛池模板: 澎湖县| 龙江县| 都匀市| 永川市| 辽宁省| 定边县| 淳安县| 若羌县| 栾川县| 千阳县| 台安县| 宝山区| 黑水县| 广平县| 东阳市| 确山县| 泸州市| 棋牌| 临西县| 林西县| 华安县| 永川市| 炎陵县| 北流市| 云梦县| 团风县| 永康市| 兴隆县| 邵东县| 阜城县| 临澧县| 禄劝| 长阳| 汝阳县| 日照市| 铜梁县| 米脂县| 阜平县| 寿光市| 库伦旗| 新巴尔虎左旗|