Skip to content

Latest commit

 

History

History
93 lines (62 loc) · 1.72 KB

File metadata and controls

93 lines (62 loc) · 1.72 KB

this keyword in JavaScript



What is this?


JS is an OOP Language


this

=> Always refers to some object


method

=> A function defined inside an object (a function executed with .methodName())


function

=> All functions that are not methods



Cases where this is NOT window when defining function() {}


  1. this inside a method

       -> The object where the method is defined
    
  2. this inside a constructor function


When defining a method, you must always define it with function(){}!


ex)

const obj = {
    name: 'obj',
    method1: function(){
        console.log(this) // this = obj
    },
    objInObj: {
        name: 'oio',
        oioMethod(){ // ES6 Syntactic sugar: makes code short and easy to write! Allows defining functions this short way!
            console.log(this) // this = objInObj
        }
    },
    arr: [0, 1, 2],
    newArr: [],
    method2 () {
        /*
                this.arr.forEach(

                    // This is NOT a method! It's just an anonymous function I created
                    // -> cannot use this
                    function(number){
                            this.newArr.push(number*100)
                    }.bind(this) // Can use it by binding!
                                // -> But are you going to write this long...?
                                //    => The arrow function was created because of this!

                    )//obj
                    */
        (number) => {
            this.newArr.push(number * 100)
        }
    }
}


The subject that called the eventListener becomes this!

  • It is passive!
    • Changes depending on who called it