Assign "this" to a New Variable

I’m playing around with the Array prototype. Right now, I’m working on a “shuffle” method:

Array.prototype.shuffle = function(){
	var returnarr = new Array();
	var temparr = this;
	while(temparr.length){
		var shufflerand = Math.floor(Math.random()*temparr.length);
		returnarr.push(temparr[shufflerand]);
		temparr.splice(shufflerand, 1);
	}
	return returnarr;
}

var arrA = new Array("Apples", "Bananas", "Cherries");
var arrB = arrA.shuffle();
alert(arrB); // for example: Bananas,Apples,Cherries
alert(arrA); // empty

The method returns a shuffled array, just as I’d expect. What I didn’t expect, though, is that it simultaneously empties the original array, arrA.

I ran this code through Firebug, and whenever the “temparr.splice” line runs, a value is removed from this, not just temparr. The reason I assigned this to the variable temparr was so that I could splice values from the middle of temparr without affecting this. However, it seems that temparr is acting as a reference to this rather than a copy.

How can I make this copy itself into the variable temparr so that we can safely splice values from temparr without affecting the original array?

A common technique is to use the slice method to slice nothing off, effectively cloning the array.

slice does not alter the original array, but returns a new “one level deep” copy that contains copies of the elements sliced from the original array


var temparr = this.slice(0);

That does it! I had forgotten that objects got passed as references rather than values when assigned to variables. Thanks!