Understanding the Keyword ‘THIS’ in JavaScript

Video

JavaScript Notes

JavaScript
    // this.js
    // Understanding what “this” is
    // “use strict”; - means you have to specify the object, calling the function, otherwise this will return undefined
    
    let box = document.querySelector('.box');
    let log = console.log;
    let myFunc = function( ){
    	log('1', this);				// this refers to the object that called the function
    };
    let myFunc2 = ( ) => {
    	log('2', this);				// this refers to the lexical object/scope of its parent (only for arrow functions)
    };
    
    box.addEventListener('mousedown', myFunc);
    box.addEventListener('mouseup', myFunc);
    
    myFunc( );						// object is global namespace
    myFunc.call(window);			// object is window namespace
    myFunc.call(box);				// object is box namespace
    
    myFunc2( );						// this will always refer to the scope of myFunc2
    myFunc2.call(window);			// this will always refer to the scope of myFunc2
    myFunc2.call(box);				// this will always refer to the scope of myFunc2