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
The self keyword is used to access the static members of the class present in the program.
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.
self is also window ... and top is the "topmost" ...
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() .
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.
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)
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With