Use of 'this' in closure

2019-02-25 21:42发布

问题:

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.