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

dfi*_*ecy 5 javascript

我不知道你能做到这一点,直到我在一个棘手的bug上碰到我的头撞墙,最后发现我们失败了因为一些jquery插件覆盖了逃生功能.所以这将提出一个警告和docwrite null:

escape = function(a){alert(a)}
document.write(escape("Need tips? Visit W3Schools!"));
Run Code Online (Sandbox Code Playgroud)

凉!(不).

有没有办法恢复原生转义功能?

Als*_*nde 13

创建一个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');
Run Code Online (Sandbox Code Playgroud)


Anu*_*rag 2

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

$.fn.naughtyJQueryPlugin = function() {
    var escape = function() { .. };
};
Run Code Online (Sandbox Code Playgroud)

如果您无法修改插件源,则将代码包装在插件周围以保留对原始转义的引用,以便稍后修复。

var origEscape = escape;

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

escape = origEscape;
Run Code Online (Sandbox Code Playgroud)


感谢@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");
Run Code Online (Sandbox Code Playgroud)

请参阅此处的示例。两个版本应该和平共处。