234 of 264 menu

this

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

Syntax

this.current object;

Example

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

<input id="elem" value="text"> let 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:

<input id="elem" value="text"> let 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:

class 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
byenru