THIS :
this refers to whatever the Object occupies in the space that this is written in. So, this has different object values depending up on the scope it is mentioned in.
Let us discuss this value in :
Global Scope
ES5 functions
ES6 functions
Objects
this value in Global Scope :
- In Global Scope, this value is empty object {}
console.log(this)
//output : {}
- Inside ES5 function, this value is Global Object
function es5Function(){
console.log(this)
}
es5Function()
//output : Object [global]
- Inside ES6 function, this value is this value in outer scope
const es6Function = ()=> console.log(this)
es6Function()
//output : {} [because the outer scope is global scope]
- Inside the method of an Object, this value is current object
const newObject = {
name : 'ben',
age : 23,
thisVal : function(){
console.log(this)
}
}
newObject.thisVal()
//output : { name: 'ben', age: 23, thisVal: [Function: thisVal] }