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

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.

主站蜘蛛池模板: 平安县| 东乡| 渭源县| 泰安市| 安宁市| 太白县| 湄潭县| 永川市| 黑水县| 金塔县| 错那县| 湘潭市| 屏边| 万州区| 郁南县| 团风县| 西乌珠穆沁旗| 抚宁县| 浪卡子县| 琼海市| 石狮市| 黔东| 南乐县| 日土县| 慈溪市| 莫力| 茂名市| 枝江市| 金阳县| 逊克县| 庄浪县| 宣汉县| 泰宁县| 怀远县| 五指山市| 澄迈县| 喜德县| 米易县| 富宁县| 包头市| 弋阳县|