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

喜你入骨 提交于 2019-12-07 05:39:35

问题


if you change native function like this:

window.open= function (a,b,c)
{
    alert(2);
}

then later you can just

delete window.open

and it would restore original function, BUT:

if you change its prototype like this:

window.__proto__.open= function (a,b,c)
{
    alert(3);
}

then delete won't do anything =\ any ideas how to restore it now?


回答1:


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.




回答2:


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] }



来源:https://stackoverflow.com/questions/21159559/delete-restore-native-function-not-working-for-changed-prototype-how-then

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