In your prod
object, you have 2 objects with the name iWantToBeMocked
. The first is the variable containing the function with your original alert; the second is contained in the returned object.
The var iWantToBeMocked
inside root.prod
is a private variable. When you set root.prod.iWantToBeMocked
, you are changing the returned function but are not touching the private member.
Now, when you use
doSomething = -> this.iWantToBeMocked()
doSomething
will look for a method attached to the context this
which happens to be root.prod
, so instead of calling the private iWantToBeMocked
it will call root.prod.iWantToBeMocked
.