Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is use of self in jquery/ javascript?

In javascript they are using like:

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

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

like image 578
geeks Avatar asked Jul 24 '15 07:07

geeks


People also ask

Why do we use self in JavaScript?

The self keyword is used to access the static members of the class present in the program.

What is self in JavaScript?

self is always within the context of an object. In JavaScript, the context is based on the calling function. If there is no calling function, then this means the global context. Inside of a browser, this is the window context, but similar idea.

What is self and top in JavaScript?

self is also window ... and top is the "topmost" ...

What does $() mean in JavaScript?

Usually when you encounter $() , that means the developer is using a javascript library, such as jQuery. The $ symbol is the namespace for those libraries. All the functions they define begin with $. , such as $. get() .


2 Answers

var self=this; is useful for when you have nested functions and this can become ambiguous (in case you dont know this is a javascript keyword). self can be used to still change the this that now reffers to the this from the inner function.

var jquery_element= $(html_element); just provides a easy way to reference the jQuery element without having to constantly recreate it (also provides performance benefit for instance explained here).

self.jquery_element = jquery_element appears to be specific to that code and I'm not quite sure what it does.

like image 123
carloabelli Avatar answered Sep 28 '22 05:09

carloabelli


It is for visibility in other scope, for using this from one scope, within other scope. 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)
       }
    }
like image 42
Alex Nikulin Avatar answered Sep 28 '22 04:09

Alex Nikulin