DEV Community

Cover image for This Keyword Scenarios in JS
Umashankar S
Umashankar S

Posted on • Edited on

This Keyword Scenarios in JS

This Keyword:-
It is an Object, that is executing the current function.
But, this keyword behaviour is different in different situations.


1. Global Space :- this keyword will always point to the global window object in global space.

console.log(this); //global window object
Enter fullscreen mode Exit fullscreen mode

2. Normal Function:- If we wrote the normal function in global space, that function will always point to the window object, so if we print "this" inside a function. that will always be widow object.

function User() {
    console.log(this) //global window object
}
User();
Enter fullscreen mode Exit fullscreen mode

3. Objects:- If we consider an object, functions inside the object will always have the parent. so "this" will not point to the global object. instead of that, it will point the particular object.

const data = {
  name: 'uma',
  age: 22,
  address: function() {
    console.log(this.age) //22
  }
}

data.address()
Enter fullscreen mode Exit fullscreen mode

Note:- But Arrow Function will always point to the window object.

const data = {
  name: 'uma',
  age: 22,
  address: () => {
    console.log(this.age) //undefined
  } 
}
data.address()
Enter fullscreen mode Exit fullscreen mode

4. Constructor:- Constructor also have the same behaviour as Objects. it will also point to the particular object.

function User(name) {
  this.name = name,
  console.log(this.name)  //uma
}

const user1 = new User('uma')
Enter fullscreen mode Exit fullscreen mode

Thanks for reading!

Top comments (1)

Collapse
 
richardknoche2 profile image
Info Comment hidden by post author - thread only accessible via permalink
Richard Knoche (He/Him)

False/ misleading: what this refers to doesn't depend on where it's used but rather on how it's called (aka its call-site). I recommend you check out the you don't know JavaScript book.

Some comments have been hidden by the post's author - find out more