繁体   English   中英

两个文件中的Javascript冲突

[英]Javascript Conflict In Two Files

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

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 我如何防止这种冲突?

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

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

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);
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM