mouseover function losing scope when called from anonymous function

喜你入骨 提交于 2020-01-05 07:28:12

问题


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:

.mouseover(save)

When called in this way, this variable is HtmlDivElement.

I tried changing the mouseover to this:

.mouseover(function(e){save(event)})

Since I'm looking for the MouseEvent. However, now this variable is Window.

I found a way to baypass this and get the HtmlDivElement by using this line of code:

.mouseover(function(e){save(this, event)})

and using this as a replacment for the this inside the function.

My question is - why is the save function losing it's scope when being called inside an anonymous function inside the mouseover binding?


回答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.



来源:https://stackoverflow.com/questions/12039146/mouseover-function-losing-scope-when-called-from-anonymous-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!