var self = this? var self = this? javascript javascript

var self = this?


This question is not specific to jQuery, but specific to JavaScript in general. The core problem is how to "channel" a variable in embedded functions. This is the example:

var abc = 1; // we want to use this variable in embedded functionsfunction xyz(){  console.log(abc); // it is available here!  function qwe(){    console.log(abc); // it is available here too!  }  ...};

This technique relies on using a closure. But it doesn't work with this because this is a pseudo variable that may change from scope to scope dynamically:

// we want to use "this" variable in embedded functionsfunction xyz(){  // "this" is different here!  console.log(this); // not what we wanted!  function qwe(){    // "this" is different here too!    console.log(this); // not what we wanted!  }  ...};

What can we do? Assign it to some variable and use it through the alias:

var abc = this; // we want to use this variable in embedded functionsfunction xyz(){  // "this" is different here! --- but we don't care!  console.log(abc); // now it is the right object!  function qwe(){    // "this" is different here too! --- but we don't care!    console.log(abc); // it is the right object here too!  }  ...};

this is not unique in this respect: arguments is the other pseudo variable that should be treated the same way — by aliasing.


Yeah, this appears to be a common standard. Some coders use self, others use me. It's used as a reference back to the "real" object as opposed to the event.

It's something that took me a little while to really get, it does look odd at first.

I usually do this right at the top of my object (excuse my demo code - it's more conceptual than anything else and isn't a lesson on excellent coding technique):

function MyObject(){  var me = this;  //Events  Click = onClick; //Allows user to override onClick event with their own  //Event Handlers  onClick = function(args){    me.MyProperty = args; //Reference me, referencing this refers to onClick    ...    //Do other stuff  }}


If you are doing ES2015 or doing type script and ES5 then you can use arrow functions in your code and you don't face that error and this refers to your desired scope in your instance.

this.name = 'test'myObject.doSomething(data => {  console.log(this.name)  // this should print out 'test'});

As an explanation: In ES2015 arrow functions capture this from their defining scope. Normal function definitions don't do that.