Basics

Challenges

Classes

Cookies

Debugging

Events

External Files

Flow Control

Forms

Functions

Html Elements

Installation

Interfaces

Keywords

Modules

Namespaces

Operators

Reference Files

String

Types

TypeScript - Arrow Functions and this

  • A regular function cares very much who calls it. The value of the this inside a regular function depends on HOW the function was called - the object that made the call. this can vary.
  • An arrow function does not care who calls it and it's this keyword inside the arrow function depends on WHERE the function was defined (the scope of the defined function)

For example (arrows), if your arrow function is defined in a class, the this will always be that Class regardless of who calls it. This is a fundamental difference from standard js functions.

'this' in regular functions == who called it? 'this' in arrow functions == where was this defined?

View the console.

Example 1
Example 2
Example 3
Example 4
Example 5

function RegFunction()
{
    // old boring global function.
    // who is "this"?  The caller.
    // it always binds the value for it's "this" keyword to the caller.
    // this might be better known as "caller" in this scenario.
    // if it didn't have an explicit caller, it is bound to the calling environment like Window.
    // this is the Window object
    console.log(`RegFunction: ${this}`);
    console.dir(this);
    return this;
}

// notice that `this` is the **person** object.
// 'this' is contained within this object scope
let person =
{
    FirstName: "Penelope",
    LastName: "Barrymore",
    FullName: function ()
    {
        console.log(`Person Obj: ${this}`);
        console.dir(this);
        return this.FirstName + " " + this.LastName;
    }
}

// notice that `this` is the window object again even though it was the car
// object who called it. Why?  Because it was defined in the Window object.
let CalculateCost = () =>
{
    console.log(`CalculateCost: ${this}`);
    console.dir(this);
    return 1000000 * 1;
}

let car =
{
    Color: "Red",
    Speed: "Fast",
    Cost: CalculateCost
}

let testerObj =
{
    // the properties of this obj are defined by functions
    FunctProp1: function(){ console.log("FunctProp1", this); return this; },
    FunctProp2: () => { console.log("FunctProp2", this); return this; }
};

$(function()
{
    $("#example1").text(RegFunction());
    $("#example2").text(person.FullName());
    $("#example3").text(car.Cost);
    $("#example4").text(testerObj.FunctProp1());
    $("#example5").text(testerObj.FunctProp2());
});