I have read articles and documents about it and w3schools says:
In a method, this refers to the owner object.
I have this method in a class App
class:
_newWorkout(e) {
e.preventDefault();
const validInputs = (...inputs) =>
inputs.every(inp => Number.isFinite(inp));
const allPositive = (...inputs) => inputs.every(inp => inp > 0);
// Get data from form
const type = inputType.value;
const distance = +inputDistance.value;
const duration = +inputDuration.value;
const { lat, lng } = this.#mapEvent.latlng;
let workout;
// If workout running, create running object
if (type === 'running') {
const cadence = +inputCadence.value;
if (
!validInputs(distance, duration, cadence) ||
!allPositive(distance, duration, cadence)
)
return alert('Inputs should be a positive number!');
workout = new Running([lat, lng], distance, duration, cadence);
}
// if workout cycling, create cycling
if (type === 'cycling') {
const elevation = +inputElevation.value;
if (
!validInputs(distance, duration, elevation) ||
!allPositive(distance, duration)
)
return alert('Inputs should be a positive number!');
workout = new Cycling([lat, lng], distance, duration, elevation);
}
// Add new object to the workout array
this.#workouts.push(workout);
// Render workout
this._renderWorkout(workout);
// Render workout on map as marker
this._renderWorkoutMarker(workout);
// Hide and clear form
this._hideForm();
// Set local storage to all workouts
this._setLocalStorage();
What i'm focusing on is the this.x
part on the bottom. What does "this" keyword refer to in that code? When I console log "this" it gives me:
App#map: i#mapEvent: Object#workouts: Array(4)__proto__: Object
So it's the "app" class. Yet when i replace "this" keyword with "App" it doesn't work. And when i console log "App" it gives me a similar but different result. Which is this:
class App {
#map;
#mapEvent;
#workouts = [];
constructor() {
this._getPosition();
this._getLocalStorage();
form.addEventListener('submit', this._newWorkout.bind(this));
inputType.a…
So, to repeat my question, what does "this" keyword actually refer to in a method? What am i missing?