从匿名函数调用时,mouseover函数失去作用域 [英] mouseover function losing scope when called from anonymous function

查看:132
本文介绍了从匿名函数调用时,mouseover函数失去作用域的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究jQuery ToolTip插件(以下称为工具提示)的代码,并且注意到我不完全了解的行为.

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绑定鼠标悬停功能,如下所示:

Tooltip binds a mouseover function like so:

.mouseover(save)

以这种方式调用时,this变量为HtmlDivElement.

When called in this way, this variable is HtmlDivElement.

我尝试将mouseover更改为此:

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

由于我正在寻找MouseEvent.但是,现在this变量是Window.

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

我找到了一种通行证,并使用以下代码获得HtmlDivElement的方法:

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

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

,并使用this代替该函数内的this.

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

我的问题是-为什么save函数在鼠标悬停绑定内的匿名函数中被调用时会失去作用域?

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

推荐答案

this的值是在每次函数调用时确定的.当您的匿名函数调用该保存"函数时,它没有做任何事情来确定this应该是什么,因此它是默认值:全局对象(窗口").

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").

您可以执行以下操作:

.mouseover(function(e){ save.call(this, e); })

使this呈现所需的值.处理程序中的this值将由框架安排,因此使用.call()会将其传递给保存"功能.

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.

要重复:在JavaScript中,this不是由代码的静态结构确定的.相反,它取决于每个单独的函数调用的情况.这意味着对于任何函数,无论其如何声明,对于任何给定的函数调用,this的值都可能是一个完全意外的结果.

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.

这篇关于从匿名函数调用时,mouseover函数失去作用域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆