This in JavaScript

This in JavaScript

“this” is one of the most misunderstood aspects of Javascript.

“this” can be thought of as an parameter passed into a function with two major differences.

  1. You can’t change the name of the parameter this.
  2. The way you send it in is different from other parameters

As a rule of thumb you should think of this as the object that calls the function.

If nothing else have been calling/invoking the function then it’s the global window object that will be calling it and also passed on as “this”.

Diffrent ways to specify which object that is calling the function:

Example 1:

var showMeThis = function() {
    console.log(this);
};
 
var object1 = {
    name: "object1",
    showMeThis : showMeThis
};

object1.showMeThis(); 

outputs:

[object Object] {
  name: "object1",
  showMeThis: function () {
    window.runnerWindow.proxyConsole.log(this);
}
}

Example 2: using call

By using .call after the functioname we can explicit control what object we want to pass into as as “this.


var showMeThis = function() {
    console.log(this);
};
 
var object1 = {
    name: "object1",
    showMeThis : showMeThis
};
 
var object2 = {
    name: "object2",
};
 
//Here we call a function and then TELL the function which object we want it to be called for
//This way it makes it clear what this will be associated with.
showMeThis.call(object2);

outputs:


[object Object] {
  name: "object2"
}

This can also be used to override the default functionality and explicit control what you want to send in as “this” into the function. For example:

object1.showMeThis.call(object2); 

//will output object2 and not object1!

IMPORTANT NOTE:

When passing a function in as a parameter, the bindings to that function will NOT be passed with it.
Example :

var eatMyFunction= function(aFunction) {
    aFunction(); //here the function gets invoked and object1 is no longer bound to the function
};

var showMeThis = function() {
  console.log(this);
};
 
var object1 = {
    name: "object1",
    showMeThis : showMeThis
};

eatMyFunction(object1.showMeThis); //it doesn't matter that object1 is bound to the function here

output from the console.log(this); inside showMeThis will be the global window object.

To pass on a callback with the bindings you can pass on a anonymous function and have it invoked from within that anonymous function
that way the binding to object1 will be passed along to the eatMyFunction in “this”.
Example:

var eatMyFunction= function(aFunction) {
    aFunction();
};

var showMeThis = function() {
  console.log(this);
};
 
var object1 = {
    name: "object1",
    showMeThis : showMeThis
};

eatMyFunction(function(){
  object1.showMeThis();
});

Add your comment