the "this" context

the "this" in global context (non-function context)

the "this" in global context (non-function context)

this ≅ global object
in Browsers: Window
in Node:global
Note, that in nodejs, the top-level scope is not the global scope. Ref: nodejs#globals_global. Each JS file is treated as a module.

the "this" in function call context

the "this" in function call context

this depends on how a function is invoked!
different ways of function invocation:
as a function
as a method
as a constructor
with apply or call or bind

Invoke as a function

in non Strict Mode

this ≅ global object
in Browsers: Window
in Node:global

            function f(){
                console.log( "this in function call:", this );
            }

            f();
            // Window
        

in Strict Mode

this = undefined

            "use strict";
            function f(){
                console.log( "this in strict function call:", this );
            }

            f();
            // undefined
        

more on Strict Mode: MDN JavaScript Reference

Invoke as a method

this = the object the method is called on


            var obj = {
                foo: function(){
                    console.log(`this = ${this}`);
                }
            };

            obj.foo();
            // this = [object Object]
        

In static (class) methods

In static methods, this refers to the class itself. Not to the object being created.
Note, that you can not invoke a static method from an object.
Reference: Classes/static @mdn

Example


            class A{
                method1(){
                    console.log(`This in method: ${this}`);
                }
                static staticMethod(){
                    console.log(`This in static method: ${this}`);
                }
            }

            let obj = new A();

            obj.method1()
            A.staticMethod()
        

Invoke as a Constructor

this = the object being constructed


            function Constructor(id){
                this.id = id;
                console.log(`this = ${this}`);
                // this = [object Object]
            };

            var obj1 = new Constructor(1);
        

This in function call - cheatsheet

thisCheatsheet.png

The "this" Pitfall and "that" Solution

The "this" Pitfall and "that" Solution

the problem

the "that" solution

Function invocation with apply()

The apply() method calls a function with a given this value, and arguments provided as an array

            func.apply(thisArg, [argsArray])
        
the this value inside function func will be equal to the object passed by thisArg argument

            const maria = {name: "Maria", age:18};

            function update(name, age){
                this.name = name;
                this.age = age;
            }

            console.log("maria before", maria);
            update.apply(maria, ["Maria Ivanova", 23]);
            console.log("maria after", maria);
        

Function invocation call()

The call() method calls a function with a given this value, and arguments provided individually (comma separated)

            func.call(thisArg, arg1, arg2, ...)
        
the this value inside function func will be equal to the object passed by thisArg argument

            const maria = {name: "Maria", age:18};
            function update(name, age){
                this.name = name;
                this.age = age;
            }

            mariaNewRecord = ["Maria Ivanova", 23];

            console.log("maria before", maria);
            update.apply(maria, mariaNewRecord );
            console.log("maria after", maria);
        

Create new function with bind()

The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.
the this value inside function func will be equal to the object passed by thisArg argument

            func.bind(thisArg[, arg1[, arg2[, ...]]])
        

            const maria = {name: "Maria", age:18};
            function update(name, age){
                this.name = name;
                this.age = age;
            }

            console.log("maria before", maria);
            var updateMaria = update.bind(maria,"Maria Ivanova", 23);

            updateMaria();
            console.log("maria after", maria);
        

"this" in addEventListener callback

"this" in addEventListener callback

"this" in addEventListener handler is the object on which the event is fired

            

            
        

"this" in setTimeout/setInterval callback

"this" in setTimeout/setInterval callback

"this" in setTimeout/setInterval handler is the Window object

            

            
        

Excercises

Excercises

Task1: Execute callback after 2 seconds ('this' problem)

See the Pen Task1: Execute callback after 2 seconds ('this' problem) by Iva Popova (@webdesigncourse) on CodePen.

Task2: Fix the bug ('this' problem)

See the Pen Task:Fix the bug ('this' problem) by Iva Popova (@webdesigncourse) on CodePen.

These slides are based on

customised version of

Hakimel's reveal.js

framework