In javascript the this
keyword change accordingly with the execution context
- in global code
this
refer to theglobal
object - inside
eval
the scope is the same as the calling context one, if no context provided then is the same as above - in all the case below if the this argument passed to
.bind
.call
or.apply
is not an object (ornull
)this
will be theglobal
object - when using a function which has been binded to a specific object using
.bind
thenthis
refers to the this argument passed to bind, the function is now permabinded. - when running a function the context is provided from the caller, if before the function call operator
()
there is a dot(.
) or a[]
operator thenthis
refers to the part on the left of such operator, unless the function is permabinded to something else or we are using.call
or.apply
if sothis
refers to the this argument unless the function was previously permabinded; - if before the function call operator
()
there neither the.
nor the[]
operators thenthis
will refer to theglobal
object (unless the function stores the result of the.bind
function) - when running a constructor function (basically when using
new
)this
refers to the object we are creating
now when using the use strict directive
things changes a bit, mostly instead of the global object when the context is not given this
will be null
, but not in all the cases.
I rarely use "use strict" so I just suggest to try it by yourself when in need.
now, what happens when a function is cached inside a variable like this:
var cache = 'A.foo'
if that you lose the context in which the original function was stored, so in this case foo will not be anymore a property on the instance A and when you run it using
cache()
the context will be evaluated using the rules I wrote above in this case the this will refer to the global
object.