this

The value this refers to the current object. This value is widely used by JavaScript, for example in functions and OOP.

Syntax

javascriptthis.current object;

Example

Let's use this to output the value of the input that loses focus to the console:

html<input id="elem" value="text">
javascriptlet input = document.querySelector('#elem');
input.addEventListener('blur', func);

function func() {
  console.log(this.value);
}

Example

Let's use this to output the value of the input that is not in focus to the console:

html<input id="elem" value="text">
javascriptlet input = document.querySelector('#elem');
input.addEventListener('blur', func);

function func() {
  console.log(this.value);
}

Example

Now let's look at the use of this in OOP. In the Student class, we will write the show function, which will show the first and last name of our student:

javascriptclass Student {
  name;
  surn;
  
  show() {
    return this.name + ' ' + this.surn;
  }
};
  
let stud = new Student;
stud.name = 'John';
stud.surn = 'Smit';
console.log(stud.show());

See also

  • the bind method
    that binds a context to a function
  • the call method
    that calls a function with a context
  • the apply method
    that calls a function with a context