Golang Tutorials - Learn Go Programming with Easy Step-by-Step Guides

Explore comprehensive Golang tutorials for beginners and advanced programmers. Learn Go programming with easy-to-follow, step-by-step guides, examples, and practical tips to master Go language quickly.

Js This Keyword in JavaScript

Js This Keyword in JavaScript

? JavaScript this Keyword

The this keyword in JavaScript refers to the context object that the current code is executing within. It’s one of the most important and sometimes confusing parts of JavaScript.


What Does this Refer To?

The value of this depends on how a function is called:

1. Global Context

In the global execution context (outside any function), this refers to the global object:

  • In browsers: window

  • In Node.js: global

console.log(this); // window (in browser)

2. Inside a Function

  • In non-strict mode, this inside a regular function refers to the global object (window in browsers).

  • In strict mode, this is undefined.

function show() {  console.log(this);}show(); // window (non-strict) or undefined (strict mode)

3. As a Method of an Object

When a function is called as a method of an object, this refers to that object.

const person = {  name: "Alice",  greet() {    console.log(this.name);  }};person.greet(); // Output: Alice

4. In a Constructor Function

When a function is used as a constructor with new, this refers to the newly created object.

function Person(name) {  this.name = name;}const p = new Person("Bob");console.log(p.name); // Bob

5. With call(), apply(), and bind()

You can explicitly set this with these methods:

function say() {  console.log(this.name);}const user = { name: "Charlie" };say.call(user);   // Charliesay.apply(user);  // Charlieconst boundSay = say.bind(user);boundSay();       // Charlie

6. Arrow Functions

Arrow functions do not have their own this. Instead, this is inherited lexically from the enclosing scope.

const obj = {  name: "Dana",  greet: () => {    console.log(this.name);  }};obj.greet(); // undefined (or window.name)

Because arrow functions don’t bind their own this, they’re often used to preserve the this context in callbacks.


Summary Table

Contextthis refers to
Global scopeglobal object (window/global)
Function call (non-strict)global object
Function call (strict mode)undefined
Method callthe object owning the method
Constructor (new)the newly created object
call/apply/bindexplicitly defined object
Arrow functionthis from surrounding scope

If you want, I can show you examples demonstrating tricky this behavior!

Disclaimer for AI-Generated Content:
The content provided in these tutorials is generated using artificial intelligence and is intended for educational purposes only.
html
docker
php
kubernetes
golang
mysql
postgresql
mariaDB
sql