what is the this in the OPP
keyword refer to the object that currently excuting in the code. it's basically represent the context in which thee code is being excuted
-
Global Context when used in the gloabl scope (outside of any function) ,
thisrefer to the global object -
Inside Function value of
thisinside regural function is how the function is called If the function is called as a method of an object,thisrefers to the object itself. Otherwise, in strict mode,thisisundefined, and in non-strict mode, it refers to the global object.function myFunction() { console.log(this); } const obj = { myMethod: myFunction, }; obj.myMethod(); // `this` refers to `obj` myFunction(); // `this` depends on strict mode or not -
Constructor function Inside a constructor function (a function used with the
newkeyword),thisrefers to the newly created instance of the object.function Person(name) { this.name = name; console.log(this); } const person1 = new Person('Alice'); // `this` refers to `person1` -
Call, Apply, and Bind Methods
These methods allow you to specify the value ofthisexplicitly when calling a function.
function greet() {
console.log(`Hello, ${this.name}!`);
}
const obj = { name: 'Alice' };
greet.call(obj); // `this` refers to `obj`
greet.apply(obj); // `this` refers to `obj`
const boundGreet = greet.bind(obj);
boundGreet(); // `this` refers to `obj`-
Arrow Functions: Unlike regular functions, arrow functions do not have their own
thiscontext. Instead, they inheritthisfrom the enclosing lexical context.const obj = { name: 'Alice', greet: () => { console.log(`Hello, ${this.name}!`); } }; obj.greet(); // `this` refers to the enclosing lexical context (usually the global object)