Online Compiler logoOnline Compiler

JavaScript Tutorial

JavaScript this Keyword: Context, Binding, and Real Behavior

The value of this depends on how a function is called, not where it is written.

Why this matters

Misunderstanding this causes many method bugs, callback issues, and interview confusion.

Context Rules for this

In object methods, this usually points to the calling object.

In regular standalone function calls, this is undefined in strict mode.

Arrow functions do not create their own this and inherit lexical this from outer scope.

Explicit Binding with call/apply/bind

call invokes function immediately with explicit this and comma-separated args.

apply is similar but accepts argument array.

bind returns a new function with permanently bound this context.

Code Examples

Method vs Arrow in Object

const user = {
  name: "Asha",
  normal() {
    return this.name;
  },
  arrow: () => this?.name,
};

console.log(user.normal()); // Asha
console.log(user.arrow());  // usually undefined

Arrow inherits outer this and is not ideal for object methods requiring dynamic context.

call and apply

function greet(city) {
  return "Hi " + this.name + " from " + city;
}
const person = { name: "Ravi" };
console.log(greet.call(person, "Pune"));
console.log(greet.apply(person, ["Delhi"]));

Both call and apply set this explicitly for invocation.

bind for Callback Safety

const profile = {
  name: "Nina",
  show() {
    console.log(this.name);
  },
};

const safeShow = profile.show.bind(profile);
safeShow();

bind prevents context loss when passing methods around.

Common Mistakes and Fixes

Using arrow functions as object methods

Use method shorthand or regular function when this is needed.

Losing this in callbacks

Use bind, wrapper functions, or class field arrows carefully.

Assuming this equals function owner always

Remember invocation style determines this value.

Frequently Asked Questions

Does this refer to current function?

No. this refers to calling context, which can vary.

When to use bind?

Use bind when passing methods as callbacks and preserving object context is necessary.

Arrow function this vs normal function this?

Arrow uses lexical this from outer scope; normal function gets dynamic this based on call site.

Is this asked in interviews often?

Yes, this binding questions are very common in JavaScript interviews.

Related JavaScript Topics