2016-11-03 38 views
0

我正在开发反应应用程序。有一些第三方库扩展了Array.prototype。他们为Array.prototype添加了额外的属性。定义数组隔离范围javascript

所以,在我的代码时,我定义

var myArray = []; 
console.log(myArray); // those extended coming with it. 

我应该如何避免这种情况。

一种方法我用这种方式尝试:

function myArray() 
{ 
    this.array = new Array(); 
    return this.array; 
} 
var myArray = myArray(); //but no luck :(
+2

使用IFrame这篇文章展示了如何抓住默认构造函数。 - > http://stackoverflow.com/questions/13990187/create-a-reset-of-javascript-array-prototype-when-array-prototype-has-been-modif – Keith

+0

你应该[修复](http:// stackoverflow.com/q/13296340/1048572)改为第三方脚本。事实上你甚至可以使这些方法不可枚举。 – Bergi

+0

@Bergi是的,我跟着这个。它几乎解决了大部分问题。问题是它也搞乱了我正在使用的其他库的代码。例如,我的应用程序是用ReactJS编写的。我正在使用React Intl进行语言支持。 React Intl行为不正确。我也无法控制该代码。如果我尝试在React Intl库中加入一些攻击。这是搞乱了默认行为。我正在考虑用新鲜的一个替换污染的Array.prototype。不幸的是coudnt找到了解决方法。以下答案的方法就好了。这不是100%。所以不能用于生产。 – NeiL

回答

0
// code extending Array.prototype 
Array.prototype.log = function(){ 
    console.log(this); 
}; 

// code extracting the native Array from an iframe 
var MyArray = getNativeArray(); 

function getNativeArray(){ 

    var iframe = document.createElement("iframe"); 
    iframe.src = "about:blank"; 
    document.body.appendChild(iframe); 
    var native = iframe.contentWindow.Array; 
    document.body.removeChild(iframe); 
    return native; 

} 

// usage and comparison 
var array1 = new Array(1,2,3); 
var array2 = new MyArray(1,2,3); 

console.log(array1);     // [1,2,3] 
console.log(array2);     // [1,2,3] 
console.log(typeof array1.log);  // "function" 
console.log(typeof array2.log);  // "undefined" 
console.log(array1 instanceof Array); // true 
console.log(array2 instanceof Array); // false 
console.log(Array.isArray(array1)); // true 
console.log(Array.isArray(array2)); // true