Use of 'this' in closure

时光毁灭记忆、已成空白 提交于 2019-12-31 03:20:30

问题


I'm just curious... how am I supposed to use 'this' within a jQuery function?

For example, if I have some code like this...

    headEl.find("form.blog-search input").focus(function() {
        $(this).next("span").animate({opacity:1}, 200);
    })

It works fine, however when linting I get the warning of "Use of 'this' in closure".

Is this something I should just ignore, or is there something I can do to not only solve the warning, but improve my code?

Update:

Based on Kevin B's comment below, I changed up the code to

    headEl.find("form.blog-search input").on('focus', function(event) {
        $(event.target).next("span").animate({opacity:1}, 200);
    })

Which works as expected... now I'm just curious, what are the downsides to this method and when should it be used in favor of this or vice-versa?


回答1:


I would say ignore jslint personally. If you really wanted to get rid of the warning you could probably do this:

headEl.find("form.blog-search input").focus(function(e) {
    $(e.currentTarget).next("span").animate({opacity:1}, 200);
})

The function passed to focus gets passed the event object.

http://api.jquery.com/event.currentTarget/




回答2:


There is no issue which your use of this in this particular closure.

The warning is probably because sometimes people expect the value of this to be the same as it was outside the closure and that is often not the case.

In your particular case you are using it correctly as the event system sets this to be the object that triggered the event.

For example, people often do an ajax call and expect the value of this to be the same inside the success handler as it was when the ajax call was made, but that is usually not the case.



来源:https://stackoverflow.com/questions/20228556/use-of-this-in-closure

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