Mouseover Function Losing Scope When Called From Anonymous Function
I'm looking into the code of the jQuery ToolTip plugin(hereinafter Tooltip), and have a noticed a behaviour I don't fully understand. Tooltip binds a mouseover function like so: .m
Solution 1:
The value of this
is established upon each function call. When your anonymous function calls that "save" function, it's not doing anything to establish what this
should be, so it's the default value: the global object ("window").
You can do this:
.mouseover(function(e){ save.call(this, e); })
to make this
take on the value you need. The this
value in the handler will be arranged by the framework, so by using .call()
you're passing it on to the "save" function.
To repeat: in JavaScript, this
is not determined by static structure of the code. Instead, it depends on the situation of each individual function call. That means that for any function, no matter how it's declared, the value of this
may be a complete surprise on any given function call.
Post a Comment for "Mouseover Function Losing Scope When Called From Anonymous Function"