【问题标题】:define array of isolate scope javascript定义隔离范围javascript数组
【发布时间】:2016-11-03 09:35:39
【问题描述】:

我正在开发 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 :(

【问题讨论】:

  • 使用 IFrame 这篇文章展示了如何获取默认构造函数。 -> stackoverflow.com/questions/13990187/…
  • 你应该fix第三方脚本。您甚至可以在事后使这些方法不可枚举。
  • @Bergi 是的,我跟着这个。它几乎解决了大部分问题。问题是它也弄乱了我正在使用的其他库的代码。例如,我的应用程序是用 ReactJS 编写的。我正在使用 React Intl 来提供语言支持。 React Intl 的行为不正确。而且我也无法控制该代码。如果我尝试在 React Intl 库中添加一些技巧。它破坏了默认行为。我正在考虑用新的替换受污染的 Array.prototype 。不幸的是,找不到解决方法。下面答案的方法很好。它不是 100%。所以不能在生产中使用。

标签: javascript arrays prototype


【解决方案1】:
// 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

【讨论】:

    猜你喜欢
    • 2023-02-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-02
    • 2017-09-22
    • 1970-01-01
    相关资源
    最近更新 更多