JavaScript Intermediate
Explain the value of 'this' in JavaScript
Overview
this is a special keyword in JavaScript. Its value is not determined at definition time, but at call time based on how the function is invoked (except for arrow functions).
Five Binding Rules
1. Default Binding
In non-strict mode, this refers to the global object (window in browsers, global in Node.js). In strict mode, it is undefined.
function show() {
console.log(this); // window (non-strict mode)
}
show();
2. Implicit Binding
When called as a method of an object, this refers to that object.
const obj = {
name: 'Alice',
greet() {
console.log(this.name); // 'Alice'
}
};
obj.greet();
3. Explicit Binding
Manually set this using call, apply, or bind.
function greet() {
console.log(this.name);
}
greet.call({ name: 'Bob' }); // 'Bob'
greet.apply({ name: 'Carol' }); // 'Carol'
const greetDave = greet.bind({ name: 'Dave' });
greetDave(); // 'Dave'
4. new Binding
When called with new, this refers to the newly created object.
function Person(name) {
this.name = name;
}
const p = new Person('Eve');
console.log(p.name); // 'Eve'
5. Arrow Function (Lexical Binding)
Arrow functions have no own this — they inherit it from the enclosing scope. call/apply/bind cannot change their this.
const obj = {
name: 'Frank',
greet: function() {
const inner = () => console.log(this.name);
inner(); // 'Frank' (inherits this from greet)
}
};
obj.greet();
Priority Order
new binding > explicit binding > implicit binding > default binding
✦ AI Mock Interview
Type your answer and get instant AI feedback
Sign in to use AI scoring
