Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
47 views2 pages

This Keyword

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
47 views2 pages

This Keyword

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 2

In JavaScript, the `this` keyword refers to the context in which a function is

called. Its value can vary depending on how a function is invoked:

1. **Global Context**: In the global execution context (outside of any function),


`this` refers to the global object. In browsers, this is the `window` object.

```javascript
console.log(this); // window in browsers
```

2. **Object Method**: When a function is called as a method of an object, `this`


refers to the object that the method was called on.

```javascript
const obj = {
name: 'Alice',
greet: function() {
console.log(`Hello, ${this.name}`);
}
};
obj.greet(); // Hello, Alice
```

3. **Constructor Functions**: When a function is used as a constructor (with the


`new` keyword), `this` refers to the newly created object.

```javascript
function Person(name) {
this.name = name;
}
const person = new Person('Bob');
console.log(person.name); // Bob
```

4. **Event Handlers**: In an event handler, `this` refers to the element that


triggered the event.

```javascript
const button = document.querySelector('button');
button.addEventListener('click', function() {
console.log(this); // <button>...</button>
});
```

5. **Arrow Functions**: In arrow functions, `this` does not have its own context;
it inherits `this` from the enclosing lexical scope.

```javascript
const obj = {
name: 'Charlie',
greet: function() {
const inner = () => {
console.log(`Hello, ${this.name}`);
};
inner();
}
};
obj.greet(); // Hello, Charlie
```
6. **Explicit Binding**: You can also explicitly bind `this` using `call()`,
`apply()`, or `bind()` methods.

```javascript
function greet() {
console.log(`Hello, ${this.name}`);
}
const person = { name: 'Diana' };
greet.call(person); // Hello, Diana
```

Understanding how `this` works is crucial for mastering JavaScript, especially when
dealing with objects and functions.

You might also like