简体   繁体   English

两个文件中的Javascript冲突

[英]Javascript Conflict In Two Files

I use a prototype in my project: 我在项目中使用了一个原型:

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

We have to add our client javascript file to our project. 我们必须将客户端javascript文件添加到我们的项目中。 They have a code like this: 他们有这样的代码:

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

map in our code, return to them Array.prototype.map . 在我们的代码中映射,返回它们到Array.prototype.map How could I prevent such conflict? 我如何防止这种冲突?

This conflict happens in local only. 此冲突仅在本地发生。 In production there is no any conflict problem. 在生产中没有任何冲突问题。

The only bullet proof solution would be to ask them not to monkeypatch prototypes of native object. 唯一的防弹解决方案是让他们不要对原始对象的原型进行猴子修补。 Or at least do it in spec conformant way if they were doing it to polyfill native methods in older browsers. 或者,如果他们这样做是为了在旧版浏览器中多填充本机方法,则至少要以符合规范的方式进行。

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

   };
}

If this is not an option due to some contract obligations. 如果由于某些合同义务而不可取。 You have the following options: 您有以下选择:

You can save native versions of monkeypatched methods before they did it. 您可以先保存monkeypatched方法的本机版本,然后再进行操作。

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

// usage
safeMap(myArray, callback, thisArg)

If they "only" missed thisArg in their map implementation you can make sure you always pass prebinded functions 如果他们在地图实现中“仅”错过了thisArg ,则可以确保始终传递预绑定函数

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

Or even monkeypatch their implementation to start Eternal Monkeypatchers War 甚至是猴子补丁的实施,从而引发了永恒的猴子补丁战争

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