5

is there a way to copy a global object (Array,String...) and then extend the prototype of the copy without affecting the original one? I've tried with this:

var copy=Array;
copy.prototype.test=2;

But if i check Array.prototype.test it's 2 because the Array object is passed by reference. I want to know if there's a way to make the "copy" variable behave like an array but that can be extended without affecting the original Array object.

mck89
  • 18,918
  • 16
  • 89
  • 106
  • I assume that first line actually reads: `var copy=Array;` – Sean Hogan Mar 02 '10 at 12:02
  • For creating an Array-like "class" see http://stackoverflow.com/questions/366031/implement-array-like-behavior-in-javascript-without-using-array It also seems like you don't understand Javascript inheritance. You should Google something like "Javascript prototypal inheritance". – Sean Hogan Mar 03 '10 at 00:01

3 Answers3

2

Good question. I have a feeling you might have to write a wrapper class for this. What you're essentially doing with copy.prototype.test=2 is setting a class prototype which will (of course) be visible for all instances of that class.

Codesleuth
  • 10,321
  • 8
  • 51
  • 71
  • Have you got some example for the wrapper class? – mck89 Mar 02 '10 at 13:32
  • @mck89: sorry, I hadn't noticed your comment on here. S.O.'s notice feature needs some work, lol. I take it you managed to get a wrapper class sorted? – Codesleuth Mar 04 '10 at 09:38
1

I think the reason the example in http://dean.edwards.name/weblog/2006/11/hooray/ doesn't work is because it's an anonymous function. So, instead of the following:

// create the constructor
var Array2 = function() {
  // initialise the array
};

// inherit from Array
Array2.prototype = new Array;

// add some sugar
Array2.prototype.each = function(iterator) {
// iterate
};

you would want something like this:

function Array2() {

}
Array2.prototype = new Array();

From my own testing, the length property is maintained in IE with this inheritance. Also, anything added to MyArray.prototype does not appear to be added to Array.prototype. Hope this helps.

Russell
  • 11
  • 1
0

Instead of extending the prototype, why don't you simply extend the copy variable. For example, adding a function

copy.newFunction = function(pParam1) { 
      alert(pParam1);
};
mck89
  • 18,918
  • 16
  • 89
  • 106
MLefrancois
  • 768
  • 5
  • 12
  • Because in this way if i create a new instance of copy it won't have the method because it will take only prototype methods. Anyway this doesn't solve the problem because it extends the original Array object too. – mck89 Mar 02 '10 at 13:38