2016-11-03 33 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