HomeAbout

What is this

The this keyword refers to the context where a piece of code, such as a function's body, is supposed to run.

Most typically, it is used in object methods, where this refers to the object that the method is attached to.

  • thus allowing the same method to be reused on different objects.

Function Counterpart

In plain object:

const test = { prop: 42, func: function () { return this.prop; }, }; console.log(test.func()); // 42

In function:

function getThis() { return this; } const obj1 = { name: "obj1" }; const obj2 = { name: "obj2" }; obj1.getThis = getThis; obj2.getThis = getThis; console.log(obj1.getThis()); // { name: 'obj1', getThis: [Function: getThis] } console.log(obj2.getThis()); // { name: 'obj2', getThis: [Function: getThis] }
AboutContact