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
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
Share Improve this question edited Jul 24, 2015 at 8:06 carloabelli 4,3493 gold badges46 silver badges71 bronze badges asked Jul 24, 2015 at 7:57 geeksgeeks 2,0556 gold badges33 silver badges49 bronze badges5 Answers
Reset to default 6var 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.
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)
}
}
To answer your direct question, this
is a javascript keyword, and its value will change depending on its location. By writing its value to a regular variable like self
, you are preserving the value wherever self
is in scope, even if this
itself has changed.
Assigning this
to another variable is useful when you have nested functions. For instance:
jQuery(function($) {
$('#myInput').on('keyup', function() {
var $this = $(this); // assign the jQuery's element to $this
$('div.errors').each(function() {
console.log($(this)); // outputs jQuery's object div.errors
console.log($this); // the input is still available in the nested function
});
});
});
As a recommendation, if a variable stores a jQuery
element, please prepend it with $
. Therefore, it should be
var $jquery_element = $(html_element);
var jquery_element= $(html_element);
is to make the html element be a jquery object that can be use with all the method of jquery.
html_element.fadeOut();
<-- will not work
$(html_element).fadeOut();
<-- will work