In JavaScript, this
refers to the object that the current function is a method of. The value of this
depends on how the function is called, and it can be explicitly set using the call
, apply
, or bind
methods.
Here are three ways this
can be used in JavaScript:
- In a method:
In this example,
const obj = { name: 'John', greet: function () { console.log(`Hello, my name is ${this.name}`); }, }; obj.greet(); // Hello, my name is John
this
refers to the objectobj
because thegreet
function is a method ofobj
. - In a constructor:
In this example,
function Person(name) { this.name = name; this.greet = function () { console.log(`Hello, my name is ${this.name}`); }; } const john = new Person('John'); john.greet(); // Hello, my name is John
this
refers to the new object that is being created when thePerson
constructor is called withnew
. Thename
andgreet
properties are added to the new object, andthis
is used to refer to the new object inside the constructor and thegreet
method.