0

Please tell me the behaviour of this in both situations. Why one shows 'window' and the other 'object'. Though they are called in the same manner by callback.

CASE: 1

let army = {
    minAge: 18,
    maxAge: 27,
    canJoin(user) {
        console.log(this);
    }
  };

function karan(callback){
    
    callback(); 
}  

karan(army.canJoin);

Result is WINDOW OBJECT

CASE: 2

let army = {
    minAge: 18,
    maxAge: 27,
    canJoin(user) {
        console.log(this);
    }
  };


function karan(callback){
    
    callback(); 
}  


karan( () => army.canJoin());

RESULT: THE OBJECT

Thelostcause
  • 105
  • 6
  • Does this answer your question? [Why do I lose the context of this in Javascript?](https://stackoverflow.com/questions/16382165/why-do-i-lose-the-context-of-this-in-javascript) – dipea Jun 20 '20 at 16:31

2 Answers2

0

this is a context object, it will be passed to the function at the time of execution. One of the ways to specify the context is through calling it as a method on an object.

CASE: 1

You are sending only the function army.canJoin to karan as callback

karan(army.canJoin);

At this point the function is detached from the original context object, then you are executing it when you call callback()

function karan(callback){
    callback(); // when the function is called here, there is no explicit context,
    // `this` will default to the window object in browser environment.
} 

CASE: 2

The function is executed when the original context is attached to it

army.canJoin() // the context or `this` is still army object

Note that for this specific case. It's not related to the arrow function, if you do the following, you will still get this as the army object

karan(function(){ army.canJoin() })
thammada.ts
  • 4,126
  • 2
  • 14
  • 26
-1

In case 1, you're experiencing what's sometimes called "context loss". Once the function army.canJoin has been passed into karan, it loses the "context" of army, so this defaults to being the window object.

In case 2, where you do army.canJoin(), you are calling canJoin "as a method of army", rather than as a standalone function. This means this will be the object which you're using to access canJoin via the dot operator.

for more information: https://stackoverflow.com/a/16382577/9011089

dipea
  • 73
  • 1
  • 9