gpt4 book ai didi

两个文件中的 Javascript 冲突

转载 作者:行者123 更新时间:2023-12-03 06:22:59 33 4
gpt4 key购买 nike

我在我的项目中使用原型(prototype):

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 。我怎样才能避免这种冲突?

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

最佳答案

唯一的解决方案是要求他们不要对 native 对象的原型(prototype)进行猴子补丁。或者至少以符合规范的方式进行,如果他们在旧版浏览器中这样做是为了填充 native 方法。

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

};
}

如果由于某些契约(Contract)义务而无法选择此选项。您有以下选择:

您可以在猴子补丁方法执行之前保存 native 版本。

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

// usage
safeMap(myArray, callback, thisArg)

如果他们“仅”在 map 实现中错过了 thisArg,您可以确保始终传递预绑定(bind)函数

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

或者甚至对他们的实现进行猴子补丁以启动永恒的猴子补丁 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);
}
}

关于两个文件中的 Javascript 冲突,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38782343/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com