两个文件中的Javascript冲突

我在项目中使用了一个原型:

NodeParser.prototype.getChildren = function(parentContainer) {
    return flatten([].filter.call(parentContainer.node.childNodes, renderableNode).map(function(node) {
    var container = [node.nodeType === Node.TEXT_NODE && !(node.parentNode instanceof SVGElement) ? new TextContainer(node, parentContainer) : new NodeContainer(node, parentContainer)].filter(nonIgnoredElement);
    return node.nodeType === Node.ELEMENT_NODE && container.length && node.tagName !== "TEXTAREA" ? (container[0].isElementVisible() ? container.concat(this.getChildren(container[0])) : []) : container;
  }, this));
};

我们必须将客户端javascript文件添加到我们的项目中。他们有这样的代码:

Array.prototype.map = function(fnc) {
 //code block
}

在我们的代码中映射,返回给他们Array.prototype.map我该如何防止这种冲突?

此冲突仅在本地发生。在生产中没有任何冲突问题。

尤里·塔拉班波(Yury Tarabanko)

唯一的防弹解决方案是让他们不要对原始对象的原型进行猴子补丁处理。或者,如果他们这样做是为了在旧版浏览器中多填充本机方法,则至少要以符合规范的方式进行。

if(typeof Array.prototype.map !== 'function') {
   Array.prototype.map = function mapPolyfil() {

   };
}

如果由于某些合同义务,这不是一个选择。您有以下选择:

您可以先保存monkeypatched方法的本机版本,然后再进行操作。

 var safeMap = Function.bind.call([].map);

// usage
safeMap(myArray, callback, thisArg)

如果他们“唯一”错过thisArg了他们的地图实现,则可以确保始终传递预绑定函数

array.map(function(){}.bind(this))

甚至是猴子补丁的实施,从而引发了永恒的猴子补丁战争

if(Array.prototype.map.length === 1) { //was patched
    var theirMap = Array.prototype.map;
    Array.prototype.map = function(fn, thisArg) {
       if(arguments.length === 2) {
          fn = fn.bind(thisArg)
       }

       return theirMap.call(this, fn);
    }
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章