简体   繁体   中英

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. They have a code like this:

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

map in our code, return to them 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.

 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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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