What is the reason for var $this = this

后端 未结 6 1779
一生所求
一生所求 2020-12-14 18:26

I\'m not the best at jquery and I came across a var initialization that I don\'t know why the person who wrote the code did it this way.

In the init for a plugin, we

6条回答
  •  情深已故
    2020-12-14 19:11

    In actuality jQuery is a wrapper around the JavaScript DOM, both enhancing and simplifying it. Very briefly JQuery selectors return JQuery Object/s i.e.

    var jQueryResults = $("article"); //Contains all article elements in the DOM as JQuery objects
    

    However, selecting elements with Javascript returns HTML DOM elements i.e.

    var normalResults = document.getElementsByTagName("article");//Contains all article elements in the DOM as HTML objects
    

    The issues arise in that DOM objects do not provide the same functionality that JQuery objects provide.

    Here is an event example which illustrates the difference:

    $('.changeColorHover').hover(function() {
        this.attr("style", "color:red");
    }); //Will not work as we are trying to call a JQuery method on a DOM object
    

    With the above mentioned in mind the 'this' keyword is a DOM object and thus you are required to convert it to a jQuery object in order to utilise jQuery methods.

     $('.changeColorHover').hover(function() {
            $(this).attr("style", "color:red");
     }); //Will work since we have first converted the DOM object to a JQuery object
    

    To sum up, the this keyword, allows you to access the object that called the event as this will give a reference to the object that raised the event. But, this is a DOM object, not a jQuery object. As a result, any of the jQuery methods you'd like to use aren't available, unless you convert it to a jQuery object.

提交回复
热议问题