Writing a prototype function in JavaScript
21 of June2008
This has been tested in FF3, IE7.
Say you wanted to add a function that would be inherent to an element, say you wanted to write an “arrayName.clone()” method (as found in java, but not JavaScript). Here’s how:
<script type="text/javascript">
Array.prototype.clone = function (){
var newArray = new Array(this.length);
for(var i=0; i < this.length; i++ ){
newArray[i] = this[i];
}
return newArray;
}
</script>
This would have the same effect as the following code:
<script type="text/javascript">
function cloneArray(oldArray){
var newArray = new Array(oldArray.length);
for(var i=0; i < oldArray.length; i++ ){
newArray[i] = oldArray[i];
}
return newArray;
}
</script>
The difference here being that for the prototype function you call it by using “arrayName.clone()” and for the second function you use cloneArray(arrayName). The both functions return the same thing.
Why not just use the following code below, you might ask? Because what you are doing below is just creating a new reference to the same array object. So if you made changes to oldArray, newArray would reflect those same changes. The functions above actually create and return a brand new array.
var oldArray = new Array(); var newArray = oldArray;
Tags: JavaScript
Posted in JavaScript |
RSS 2.0 Feed for comments