[javascript] var self = this?

Using instance methods as callbacks for event handlers changes the scope of this from "My instance" to "Whatever just called the callback". So my code looks like this

function MyObject() {
  this.doSomething = function() {
    ...
  }

  var self = this
  $('#foobar').bind('click', function(){
    self.doSomethng()
    // this.doSomething() would not work here
  })
}

It works, but is that the best way to do it? It looks strange to me.

This question is related to javascript jquery scope closures

The answer is


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.


One solution to this is to bind all your callback to your object with javascript's bind method.

You can do this with a named method,

function MyNamedMethod() {
  // You can now call methods on "this" here 
}

doCallBack(MyNamedMethod.bind(this)); 

Or with an anonymous callback

doCallBack(function () {
  // You can now call methods on "this" here
}.bind(this));

Doing these instead of resorting to var self = this shows you understand how the binding of this behaves in javascript and doesn't rely on a closure reference.

Also, the fat arrow operator in ES6 basically is the same a calling .bind(this) on an anonymous function:

doCallback( () => {
  // You can reference "this" here now
});

I think it actually depends on what are you going to do inside your doSomething function. If you are going to access MyObject properties using this keyword then you have to use that. But I think that the following code fragment will also work if you are not doing any special things using object(MyObject) properties.

function doSomething(){
  .........
}

$("#foobar").ready('click', function(){

});

I haven't used jQuery, but in a library like Prototype you can bind functions to a specific scope. So with that in mind your code would look like this:

 $('#foobar').ready('click', this.doSomething.bind(this));

The bind method returns a new function that calls the original method with the scope you have specified.


I think it actually depends on what are you going to do inside your doSomething function. If you are going to access MyObject properties using this keyword then you have to use that. But I think that the following code fragment will also work if you are not doing any special things using object(MyObject) properties.

function doSomething(){
  .........
}

$("#foobar").ready('click', function(){

});

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
  }
}

I haven't used jQuery, but in a library like Prototype you can bind functions to a specific scope. So with that in mind your code would look like this:

 $('#foobar').ready('click', this.doSomething.bind(this));

The bind method returns a new function that calls the original method with the scope you have specified.


Just adding to this that in ES6 because of arrow functions you shouldn't need to do this because they capture the this value.


Just adding to this that in ES6 because of arrow functions you shouldn't need to do this because they capture the this value.


One solution to this is to bind all your callback to your object with javascript's bind method.

You can do this with a named method,

function MyNamedMethod() {
  // You can now call methods on "this" here 
}

doCallBack(MyNamedMethod.bind(this)); 

Or with an anonymous callback

doCallBack(function () {
  // You can now call methods on "this" here
}.bind(this));

Doing these instead of resorting to var self = this shows you understand how the binding of this behaves in javascript and doesn't rely on a closure reference.

Also, the fat arrow operator in ES6 basically is the same a calling .bind(this) on an anonymous function:

doCallback( () => {
  // You can reference "this" here now
});

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.


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
  }
}

I haven't used jQuery, but in a library like Prototype you can bind functions to a specific scope. So with that in mind your code would look like this:

 $('#foobar').ready('click', this.doSomething.bind(this));

The bind method returns a new function that calls the original method with the scope you have specified.


var functionX = function() {
  var self = this;
  var functionY = function(y) {
    // If we call "this" in here, we get a reference to functionY,
    // but if we call "self" (defined earlier), we get a reference to function X.
  }
}

edit: in spite of, nested functions within an object takes on the global window object rather than the surrounding object.


I think it actually depends on what are you going to do inside your doSomething function. If you are going to access MyObject properties using this keyword then you have to use that. But I think that the following code fragment will also work if you are not doing any special things using object(MyObject) properties.

function doSomething(){
  .........
}

$("#foobar").ready('click', function(){

});

var functionX = function() {
  var self = this;
  var functionY = function(y) {
    // If we call "this" in here, we get a reference to functionY,
    // but if we call "self" (defined earlier), we get a reference to function X.
  }
}

edit: in spite of, nested functions within an object takes on the global window object rather than the surrounding object.


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
  }
}

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to scope

Angular 2 - Using 'this' inside setTimeout Why Is `Export Default Const` invalid? How do I access previous promise results in a .then() chain? Problems with local variable scope. How to solve it? Why is it OK to return a 'vector' from a function? Uncaught TypeError: Cannot read property 'length' of undefined Setting dynamic scope variables in AngularJs - scope.<some_string> How to remove elements/nodes from angular.js array Limiting number of displayed results when using ngRepeat A variable modified inside a while loop is not remembered

Examples related to closures

Store a closure as a variable in Swift How to map to multiple elements with Java 8 streams? groovy: safely find a key in a map and return its value Exception: Serialization of 'Closure' is not allowed JavaScript closures vs. anonymous functions Don't understand why UnboundLocalError occurs (closure) Closure in Java 7 How should I call 3 functions in order to execute them one after the other? Why aren't python nested functions called closures? Passing parameters in Javascript onClick event