Click here to Skip to main content
15,899,825 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have quite a hard time understanding this expression (split) Can someone explain it to me: 

class Chronometer {
  constructor() {
   this.currentTime = 0
   this.intervalId = null
  }

getMinutes() {
    return this.currentTime/60
  }

 getSeconds() {
    return this.currentTime%60
  }

computeTwoDigitNumber(value) {
     return String("0" + value).slice(-2)
  }

split () {
      var minutes = this.computeTwoDigitNumber(this.getMinutes());
      var seconds = this.computeTwoDigitNumber(this.getSeconds());
      printSplit(minutes, seconds)

What I have tried:

I understand 'this' referring to an object but in this case then what does 'object.function' means ?
Posted
Updated 12-Dec-21 5:02am

The term this is an object reference. So any expression of the from this.X is a reference to a property of the object, and this.Y() is a call to a function, defined in the class. In the case above split, computeTwoDigitNumber, getMinutes and getSeconds, are all functions of the Chronometer class. That is they can be called from inside the class using the this reference, or from elsewhere by using an instance of the Chronometer class. See JavaScript Objects[^].
 
Share this answer
 
The class Chronometer contains functions called getMinutes, getSeconds, computeTwoDigitNumber, and split.
These act upon the current instance of the class when they are called, and in your split function they are called on the current instcne, called this. Inside a class, thisalways refers to the current instance of that class.

It's similar to cars: I have MyCar, you have YourCar. Those are separate instances of teh class Car and you already know that MyCar is not the same as YourCar - MyCar is a black Mercedes, YourCar is a a green Ford.
But if we refer to "this car" it could be either, and asking the question "What colour is this car?" will give us different results depending on which actual vehicle we are pointing at.
In car terms, this always references the current instance of a car and the questions we ask, the actions we take, the places we drive to are independent of which physical car we are talking about:
this.DriveTo("THE SHOPS")
is the same for YourCar as it is for MyCar.

The this keyword does the same thing in javascript: it says "call this function / access this value / change this detail" on the current class instance.

Make sense now?
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900