What is the use of self in jquery / javascript?

In javascript they use like:

  • var self=this;
  • var jquery_element= $(html_element);
  • self.jquery_element=jquery_elemnet

Why do we use them in javascript. I got this code from OpenStack horizon

+4
source share
5 answers

var self=this;useful when you have nested functions, and thiscan become ambiguous (if you do not know this, the javascript keyword). selfcan be used for change this, which now returns to thisfrom an internal function.

var jquery_element= $(html_element);it simply provides an easy way to reference a jQuery element without having to constantly recreate it (also provides performance benefits, such as explained here ).

self.jquery_element = jquery_element, , , , .

+5

, this javascript , . self, , self , this.

+3

, this . Edit.

 var parentFunction = function(){
       this.msg = "hello world";
       var parentScopeSelf = this;
       var innerFunction = function(){
            var innerFunctionScopeSelf = this;
            console.log(this.msg);// undefined (because this now is   innerFunction scope, and does not have property msg)
            console.log(innerFunctionScopeSelf.msg);// undefined (because innerFunctionScopeSelf is "this" from  innerFunction scope, and does not have property msg)
            console.log(parentScopeSelf.msg);// hello world (because parentScopeSelf is "this" from parentFunction scope)
       }
    }
+3

this , . :

jQuery(function($) {
    $('#myInput').on('keyup', function() {
        var $this = $(this); // assign the jQuery element to $this
        $('div.errors').each(function() {
            console.log($(this)); // outputs jQuery object div.errors
            console.log($this); // the input is still available in the nested function
        });
    });
});

, jQuery, $. ,

var $jquery_element = $(html_element);
+1

var jquery_element= $(html_element);

the html element is to be a jquery object that can be used with all jquery methods.

html_element.fadeOut(); <- will not work

$(html_element).fadeOut(); <- will work

+1
source

Source: https://habr.com/ru/post/1599459/


All Articles