开发者

Copy and extend global objects in javascript

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.


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.


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.


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜