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.

2
  • I assume that first line actually reads: var copy=Array; Commented Mar 2, 2010 at 12:02
  • For creating an Array-like "class" see stackoverflow.com/questions/366031/… It also seems like you don't understand Javascript inheritance. You should Google something like "Javascript prototypal inheritance". Commented Mar 3, 2010 at 0:01

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Have you got some example for the wrapper class?
@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?
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.

Comments

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);
};

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.