“delete” - restore native function not working for changed prototype, how then?

我怕爱的太早我们不能终老 提交于 2019-12-05 09:04:25

When you change window.open to something else, e.g. using window.open = 'something else';, then you're shadowing the open method from the prototype;

// Looking up window.open (in the prototype chain)....
window.open;           // Found, result == 'something else'
window.__proto__.open; // Not accessible any more (shadowed by previous line)

After invoking delete window.open to delete 'something else', the original method becomes visible again, because it had never disappeared from the prototype chain.

But if you've modified the open method on the prototype, e.g. window.__proto__.open = bogus;, then you cannot easily restore the old method. So, to get the "open window" behavior again, you need to either keep a reference to the original method before replacing it,

var original_open = window.open;
window.__proto__.open = 'bogus';
// .... whatever ....
// Now restore it:
window.__proto__.open = original_open;

Or borrow it from another window, e.g. using a temporary new frame:

var frame = document.createElement('iframe');
document.body.appendChild(frame);
window.__proto__.open = frame.contentWindow.open;
frame.parentNode.removeChild(frame);

This whole idea is ridiculous though: You should not break built-in methods.

delete window.open;

(function(func) {
    var frame = document.createElement('iframe');
    document.body.appendChild(frame);
    // Intentionally set in global scope
    window[func] = frame.contentWindow[func];
    frame.parentNode.removeChild(frame);
})("open");

open

ƒ open() { [native code] }

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!