Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/451.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 覆盖本机转义函数后恢复本机转义函数的方法?_Javascript - Fatal编程技术网

Javascript 覆盖本机转义函数后恢复本机转义函数的方法?

Javascript 覆盖本机转义函数后恢复本机转义函数的方法?,javascript,Javascript,我不知道你能做到这一点,直到我在一个麻烦的bug上撞到了墙上,最终发现我们失败了,因为一些jquery插件覆盖了转义函数。因此,这将显示一个警报和docwrite null: escape = function(a){alert(a)} document.write(escape("Need tips? Visit W3Schools!")); 酷!(不是) 有没有办法恢复本机转义功能?扔掉那个插件,因为你不知道里面隐藏着什么邪恶。如果你不能做到这一点,那么最理想的解决方案就是在escape之

我不知道你能做到这一点,直到我在一个麻烦的bug上撞到了墙上,最终发现我们失败了,因为一些jquery插件覆盖了转义函数。因此,这将显示一个警报和docwrite null:

escape = function(a){alert(a)}
document.write(escape("Need tips? Visit W3Schools!"));
酷!(不是)


有没有办法恢复本机转义功能?

扔掉那个插件,因为你不知道里面隐藏着什么邪恶。如果你不能做到这一点,那么最理想的解决方案就是在escape之前放置一个
var
关键字,这样它就不会泄漏到全局范围,并保持在插件函数中

$.fn.naughtyJQueryPlugin = function() {
    var escape = function() { .. };
};
如果您无法修改插件源代码,那么将代码包装在插件周围,以保留对原始转义的引用,您可以稍后修复该引用

var origEscape = escape;

$.fn.naughtyJQueryPlugin = function() {
    ...
};

escape = origEscape;


多亏@Tim指出,如果你能总结一下插件源代码,这里有一个更强大的技术:

(function(escape) {
    $.fn.naughtyJQueryPlugin = function() {
        // any change to escape (not window.escape) will affect the parameter
        // we passed in the outer function to which we have a reference 
        // through a closure.
        // This avoids manipulating the plugin's source, and still have both
        // versions intact.
    };
})(escape); // pass the global escape as a parameter

// should call the global escape
escape("hello");

// when plugin is called, overridden escape should be called
$("div").naughtyJQueryPlugin("message");

参见示例。这两个版本应该和平共存。

如果您可以在插件之前添加代码,您可以“保存”原始功能:

oldescape = escape;
function fix() {
    escape = oldescape;
}

创建iframe并从中获取函数:

function retrieveNative(native) {
  var iframe = document.createElement('iframe');
  document.body.appendChild(iframe);
  var retrieved = iframe.contentWindow[native];
  document.body.removeChild(iframe);
  return retrieved;
}

window.escape = retrieveNative('escape');

在后一种情况下,这可能会破坏插件:它将在函数中重新定义
escape
,然后escape wu将立即重置为其原始值,然后调用
顽皮jqueryplugin
将使用原始的escape函数,而不是插件的版本。@Tim-感谢您的提示。关闭可能会更好地解决问题。更新的答案。谢谢你的回答,最好是放弃插件或修复它,但它超出了我的控制范围。我想我可以保存旧的escape并将其还原。请记住,对于某些功能来说,将其附加到
窗口
对象非常重要:例如,window.getSelection在其他情况下不起作用。我很惊讶它能起作用,并且没有跨域问题。好发现@Scharrels:您仍然可以使用apply和bind来运行函数,将window作为“this”对象。这实际上不起作用,因为现代浏览器会破坏已删除窗口上的对象以进行垃圾收集。