Interview question
What is the this keyword in JavaScript and how does its value get determined? JavaScript में this keyword क्या है और इसकी value कैसे determine होती है?
Answer
The this keyword refers to the object that the function is called on. Its value is determined at call time, not definition time.
// 1. Global context
console.log(this); // Window (browser) or global (Node.js)
// 2. Object method
const obj = {
name: 'John',
greet: function() {
console.log(this.name); // 'John' - this refers to obj
}
};
obj.greet();
// 3. Constructor function
function Person(name) {
this.name = name; // this refers to the new object being created
}
const p = new Person('Jane');
// 4. Arrow function (no own this)
const obj2 = {
name: 'Bob',
greet: () => {
console.log(this); // Window or global, not obj2!
}
};
// 5. call(), apply(), bind()
const person1 = { name: 'Alice' };
const person2 = { name: 'Charlie' };
function printName() {
console.log(this.name);
}
printName.call(person1); // 'Alice'
printName.apply(person2); // 'Charlie'
const boundFunc = printName.bind(person1);
boundFunc(); // 'Alice'| Context | this refers to |
|---|---|
| Method call (obj.method()) | The object (obj) |
| Function call (func()) | Global object or undefined (strict mode) |
| Constructor (new Class()) | The newly created instance |
| Arrow function | Lexical this from surrounding scope |
Interview tip: Emphasize that this is determined at call time, not definition time. Arrow functions don't have their own this - they use the enclosing scope's this.
The this keyword उस object को refer करता है जिस पर function को call किया जाता है। Its value call time पर determine होती है, definition time पर नहीं।
// 1. Global context
console.log(this); // Window या global
// 2. Object method
const obj = {
name: 'John',
greet: function() {
console.log(this.name); // 'John'
}
};
obj.greet();
// 3. Constructor
function Person(name) {
this.name = name;
}
const p = new Person('Jane');
// 4. Arrow function (अपना this नहीं)
const obj2 = {
name: 'Bob',
greet: () => {
console.log(this); // Window, obj2 नहीं!
}
};
// 5. call(), apply(), bind()
const person1 = { name: 'Alice' };
function printName() {
console.log(this.name);
}
printName.call(person1); // 'Alice'
| Context | this refer करता है |
|---|---|
| Method call (obj.method()) | Object (obj) |
| Function call (func()) | Global या undefined (strict mode) |
| Constructor (new Class()) | नया instance |
| Arrow function | Surrounding scope का this |
इंटरव्यू टिप: Emphasize करें this call time पर determine होता है। Arrow functions अपना this नहीं रखते - enclosing scope का this use करते हैं।
Was this answer clear?