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());