Extending Prototype - cloning arrays

written by Tobie on August 11th, 2006 @ 07:46 PM

Not long ago, I posted a JavaScript Quick Tip entitled a truly new array. As I needed this feature for one of the projects I'm working on, I decided to extend my favorite JavaScript framework (aka Prototype) so as to include it.

The code is pretty basic:

Object.extend(Array.prototype, {
  clone: function(){
    return [].concat(this);
  }
});

and here's how you use it:

var animals = ['horse', 'dog', 'penguin'];
var mammals = animals.clone();
mammals.pop();
alert(animals); // returns 'horse, dog, penguin'
alert(mammals); // returns 'horse, dog'

It is using Prototype's Object.extend() method to add the clone() method to every instance of the Array object.

The clone() method simply creates a new Array object (using the shorthand syntax []) which it populates with the content of the array instance (referred by this) using the concat() method.

Hope you find it useful!

Update: this code is now downloadable as part of xPrototype, my tiny add-on to Prototype.

Update (Oct. 17. 2006): this code is no longer part of xPrototype as it has been added to Prototype Trunk.

Comments

Comments are closed