Can you alter a Javascript function after declaring it?

前端 未结 12 819
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-28 22:10

Let\'s say I have var a = function() { return 1; }. Is it possible to alter a so that a() returns 2? Perhaps by editing a

12条回答
  •  囚心锁ツ
    2020-11-28 22:47

    So you want to modify the code of a function directly, in place, and not just reassign a different function to an existing variable.

    I hate to say it, but as far as I have been able to figure it out - and I have tried -, it can't be done. True, a function is an object, and as such it has methods and properties which can be tweaked and overwritten on the object itself. Unfortunately, the function body is not one of them. It is not assigned to a public property.

    The documentation on MDN lists the properties and methods of the function object. None of them gives us the opportunity to manipulate the function body from the outside.

    That's because according to the spec, the function body is stored in the internal [[Code]] property of the function object, which can't be accessed directly.

提交回复
热议问题