定义数组的隔离范围javascript

define array of isolate scope javascript

本文关键字:范围 javascript 隔离 数组 定义      更新时间:2023-09-26

我正在react应用程序上工作。存在一些第三方库扩展Array.prototype的问题。它们为Array.prototype.

添加了额外的属性

那么,在我的代码中每当我定义

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 :(
// 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