I tried to proxy Function.prototype
.
I created a new Proxy
and rewrote the toString
method, however console.log('cas')
doesn’t work, why?
Function.prototype = new Proxy(Function.prototype, {
get: function(target, property, receiver) {},
set: function(target, property, value, receiver) {
console.log('cas')
}
})
Function.prototype._toString = Function.prototype.toString;
Function.prototype.toString = function() {
console.log('bb')
return this._toString()
}
2
Answers
The answer is simple:
Function.prototype
is not writable.As for why JS didn’t throw an error… It’s JS. What do you expect?
On the other hand, you can use
'use strict'
to make these kinds of error explicit (thanks @Keith).To prevent
Function#toString()
from being overwritten, you can re-define it:Try it:
Ok, we cannot overwrite
Function.prototype
but we can set the prototype ofFunction.prototype
(an evil professor’s laugh here):