What is the difference between this and self in javascript [closed]

1

I have seen that within a method or a function in javascript they make the reference this with a variable self .

    
asked by Carlos Alberto Jose Cruz 05.07.2017 в 23:57
source

1 answer

4

In javascript this, it is dependent on the context in which it is located and will change from method to method as it is dynamic.

The technique of leaving this saved in self is used to always have the original reference to the object that shot that method.

You can also find variants depending on the tastes of the developers such as:

var _this = this;

or

var thiz = this;

or

var me = this;

I'll try to illustrate with an example. In which we want to use this global in a function, and even in a function within that function.

function a(){
console.log(this); // este this no es el del handler es relativo a la funcion a

function b(){
console.log(this); // y este this tampoco es el del handler y tampoco es relativo a function a, este this es relativo a b
}

};

So how do we use the global this within these functions we use the technique of self or _this is the same, personally I prefer _this.

var _this = this;

function a(){
console.log(_this); // ahora si es el this del contexto global

 function b(){
  console.log(_this); // lo mismo aqui
 }

};
    
answered by 06.07.2017 в 00:23