Understanding `this` keyword in javascript
Tags: javascript, programming, tutorial, webdev
Published: 2024-02-10 04:48:48

The `this` keyword in JavaScript is a reference to the object that is currently executing or invoking the current method or function. It is a context-specific keyword, meaning its value changes depending on where and how it is used within your code. 

Let's see how this behaves in different contexts:


### Global Context

When used outside of any function, this refers to the global object. In a browser environment, the global object is window, 

```javascript
console.log(this === window); // true in a browser environment
```

whereas in Node.js, it's called global.

```javascript

// Define a global variable
global.myGlobalVar = 'Hello, global!';

// Use a built-in global function
setTimeout(() => {
  console.log(myGlobalVar); // Access the global variable without using 'global.' prefix
}, 1000);

// Access a global object property: process
console.log('Current version of Node.js:', process.version);

```

### Function Context

In a regular function call, this refers to the global object (non-strict mode) or is undefined (strict mode).

```javascript
function myFunction() {
  console.log(this);
}
myFunction(); // logs global object (window in browsers) or undefined in strict mode


/*node.js*/
function testFunction() {
  return this === global;
}

console.log(testFunction()); // true
```

Inside a method (a function inside an object), this refers to the object the method was called on.

```javascript

const myObject = {
  myMethod() {
    console.log(this);
  }
};
myObject.myMethod(); // logs myObject

```

### Arrow Functions

Arrow functions do not have their own this. Instead, they inherit this from the surrounding (lexical) context. This makes arrow functions particularly useful when you want to ensure that this within a function refers to the surrounding object.

```javascript

const myObject = {
  myMethod: () => {
    console.log(this);
  }
};
myObject.myMethod(); // logs global object or undefined in strict mode, because arrow functions do not bind their own this
```

### Event Handlers

In the context of DOM event handlers, this refers to the element that received the event, unless an arrow function is used or the function is bound to a different context.

```javascript

document.getElementById('myButton').addEventListener('click', function() {
  console.log(this); // refers to the element that was clicked
});

```

### Using call(), apply(), and bind() Methods: 

JavaScript provides these methods to explicitly set the value of this for any function call. call() and apply() invoke the function immediately with a specified this value, while bind() returns a new function with this bound to a specific object.

```javascript

function greet() {
  console.log(`Hello, ${this.name}`);
}

const person = { name: 'John' };
greet.call(person); // Hello, John

```

```javascript
function greet() {
  console.log(this.message);
}

const friendlyGreet = {
  message: 'Hello, friend!'
};

const strangerGreet = {
  message: 'Hello, stranger.'
};

// Using bind() to create a new function where `this` is set to friendlyGreet
const greetFriend = greet.bind(friendlyGreet);
greetFriend(); // Outputs: Hello, friend!

// Similarly, binding greet to strangerGreet
const greetStranger = greet.bind(strangerGreet);
greetStranger(); // Outputs: Hello, stranger.
```


Understanding `this` can be tricky but is important, especially when dealing with object-oriented programming concepts, event handling, and functional programming patterns.


Now, if you understood this well. What do you think will be the output here?


```javascript
var length = 10;
function fn() {
    console.log(this.length);
}

var obj = {
  length: 5,
  method: function(fn) {
    fn();
    arguments[0]();
  }
};

obj.method(fn, 1);
```