Problem Statement
In a regular function, what does this refer to in the browser?
Explanation
In non-strict mode, this in a regular function refers to the global object, which is window in browsers.
In strict mode, this is undefined in regular functions.
The value of this depends on how the function is called, not where it is defined.
In object methods, this refers to the object. In constructors with new, this refers to the newly created object. In arrow functions, this is inherited from the parent scope.
Understanding this is crucial for object-oriented JavaScript.
Code Solution
SolutionRead Only
// Global context (browser)
console.log(this); // window object
// Regular function
function show() {
console.log(this); // window (non-strict) or undefined (strict)
}
show();
// Object method
const obj = {
name: 'Object',
greet: function() {
console.log(this.name); // 'Object' (this = obj)
}
};
obj.greet();
// Arrow function (lexical this)
const obj2 = {
name: 'Object2',
greet: () => {
console.log(this.name); // undefined (this = window)
}
};
obj2.greet();
// Constructor
function Person(name) {
this.name = name; // this = new object
}
const person = new Person('John');
// Event handler
button.addEventListener('click', function() {
console.log(this); // button element
});
// Explicit binding
function greet() {
console.log(this.name);
}
const user = { name: 'Jane' };
greet.call(user); // 'Jane' (this = user)Practice Sets
This question appears in the following practice sets:
