简体   繁体   English

在javascript中复制和扩展全局对象

[英]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? 有没有办法复制全局对象(Array,String ...),然后扩展副本的原型而不影响原始对象? 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. 但是,如果我检查Array.prototype.test它是2,因为Array对象是通过引用传递的。 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. 我想知道是否有办法使“复制”变量表现得像一个数组,但可以扩展而不影响原始的Array对象。

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. 你实际上用copy.prototype.test=2做的是设置一个类原型,它将(当然)对于该类的所有实例都是可见的。

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. 我认为http://dean.edwards.name/weblog/2006/11/hooray/中的示例不起作用的原因是因为它是一个匿名函数。 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. 从我自己的测试中,使用此继承在IE中维护length属性。 Also, anything added to MyArray.prototype does not appear to be added to Array.prototype . 此外,添加到MyArray.prototype任何内容MyArray.prototype都没有添加到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);
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM