1

I have a function declaration, e.g.

function a(){alert("Hello");}

and I'd like to have a script to be run before the above script so that above function declaration have no effect, i.e. it should not throw errors and a(); should not open an alert window.

If it was a variable assignment like

var a = function (){ alert("Hello");};

I could do

Object.defineProperty(window, 'a', {value: function(){}});

so that a is not writable and assignments that happens after that has no effect.

However, the same thing seems to be impossible with function declarations. No matter how I set writable/configurable, the new function declaration is applied or it throws errors, such as

Uncaught SyntaxError: Identifier 'a' has already been declared (Chrome)
TypeError: cannot declare global binding `a': property must be configurable or both writable and enumerable (Firefox)

ES6 Proxy seemed promising, because it has defineProperty handler, but it seems to be impossible to 'proxy' the window object.

Now I have a feeling that because of how function declaration is implemented either by browsers or by ecmascript specifications, it is impossible to achieve this. Is there any way to achieve this?

Alternatively, if there is a way to get notified when a function a is declared, I could do window.a = function (){} then. Is there such a way?

1 Answer 1

1

The only way I found to do this (.watch) is Firefox specific, sadly:

<script>
function a() { console.log('no-op'); }

window.watch('a', function (prop, oldval, newval) {
    return oldval;
});
</script>

<script>
function a() { alert("Hello"); }
a();
</script>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.