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 theArray
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 adestination
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.