It's like 'this' and like that and like this and....wat??

The beginnings of a complicated relationship

Let's remember a few things about Objects:

  • Objects can have properties (values)

  • Objects can have methods (functions)

  • Objects can be empty

const myObject = {
    myProperty: 'Some Data Value',
    myMethod: function(){
        console.log('I do things');
    }
};

const emptyObject = {};

Remember these things about Functions:

  1. Whenever ANY function is invoked JavaScript with or without explicit parameters that you the programmer writes, 2 implicit parameters are also passed: 
    • arguments
    • this 
  2. this refers to the object which the current function is associated or belongs to. Otherwise known as the function context. 
    1. All functions are objects (first class objects)
    2. All objects can have properties and that functions can be properties of objects
  3. this ALWAYS refers to an instance of an Object
  4. function ALWAYS belongs to an Object

Invoking Functions

Functions can be invoked/called in 4 ways:

As a function: 

function hackThePlanet() {
    //do things to hack the planet
    //this refers to the global context or window object
}

hackThePlanet();

As a method: 

var hacker = {
    hackThePlanet: function() {
        //hack the things
        //this refers to the hacker object
    }
};

hacker.hackThePlanet();

As a constructor:

With call/apply:

TBD

TBD

The main difference between all methods is what determines the function's context or this

The easiest way to remember the previous 2 rules is that this refers to the object which the function belongs to.

If a function isn't the property of an object, it belongs to the window object or global scope.

this does not have a value until an object invokes the function where this is defined.

this is the global scope if you're just calling a function. If you're calling a property/method of an object(function is an object) this is the owning object context

Cool. Make Sense?

// What is this in the following scenarios?

function hackThePlanet() {
    console.log(this);
}

hackThePlanet(); // Invoking as a function = ???

const destroy = hackThePlanet;

destroy(); // Invoking as a ??? = ???

const hacker = {
    hackThePlanet: hackThePlanet, // assign a reference to our function defined above
    loveThePeople: function(){ 
        console.log(this); 
    }
};

hacker.hackThePlanet(); // Invoking as a ??? = ???

hacker.loveThePeople(); // ???

hacker.allTheThings = function(){
    console.log(this);
};

hacker.allTheThings(); // ???

Let's try it out:

If you can understand this...

...you can understand all of that.

WAT!

Like this and like that and like this and...wat?

By DevLeague Coding Bootcamp

Like this and like that and like this and...wat?

An exploration of the concept of this in JavaScript for only function invocation and method invocation. Constructor invokation and call/apply to come later.

  • 1,341