Search code examples
programming-languagesobjectmutation

Why not allow mutation of the this binding?


I'm building a interpreter/compiler for a school project (well now its turning into a hobby project) and an instructor warned me not to allow mutation of the 'this' binding (he said it was gross and made a huge deal about it) but I never learned why this is so... dangerous or bad. I'm very curious about why this is so bad. I figured this sort of feature could be useful in some way or another.

I'm wondering if anyone familiar with building languages can tell me what sort of problems mutation on the 'this' binding can cause, and if they know of any cool or useful tricks that one could do if it actually was allowed.

Do any languages that you're aware of allow mutation of 'this'?

Thanks,


Solution

  • I can think of several reasons why it would be a bad idea.

    1) 'this' is a pointer to the object instance on which the method call is invoked. Allowing changes to it could lead to memory access validations in the worst case.

    2) The caller expects the method to work on the instance on which it was invoked. Changing 'this' to something else would produce unexpected results.

    3) I can't think of anything that mutation of 'this' would allow that can't be achieved in a more standard, familiar way.