Marko Sudar
Marko Sudar

Reputation: 1

Need explanation for 'under the hood' of get and set in JavaScript

Given the code below even though the name of the parameter is on the beginning firstName, after setting it with setter and looking at the properties of an object it becomes _firstName. I am coming from a Java development background and this seems unlogical to me. Can somebody explain, please?

class Person {
constructor(firstName, DOB, sport) {
        this.firstName = firstName;
        this.DOB = DOB;
        this.sport = sport;
    }   
get firstName() {  
        return this._firstName;
    }
set firstName(firstName) {
        this._firstName = firstName;   
    }
}

const person1 = new Person('Marko', '2002', 'tennis');`

Object after person1.firstName = 'Luka';

(Person {_firstName: 'Luka', DOB: '1256', _sport: 'tennis'}
DOB: "1256"
_firstName: "Luka"
_sport: "tennis"
DO: undefined
firstName: (...)
sport: (...)
[[Prototype]]: Object)

I tried person1.firstName = 'Luka'; and was expecting object field to stay firstName but it became _firstName (with underline). I see that I am making this change in this line this._firstName = firstName; but I do not understand how can variable name be overriden

Upvotes: 0

Views: 365

Answers (1)

Matthias Schmidt
Matthias Schmidt

Reputation: 616

this.firstName is a method setting the property this._firstName.

Calling the setter method this.firstName = "Marko" works similar to calling a standard method like this.firstName("Marko"). Since you're using the method in your constructor it "looks like" you're setting the property this.firstName when you're actually using the method this.firstName to set the property this._firstName.

Modifying this.firstName method helps understand this:

class Person {
    constructor(firstName, DOB, sport) {
        this.firstName = firstName;
        this.DOB = DOB;
        this.sport = sport;
    }   
get firstName() {  
        return this._firstName;
    }
set firstName(firstName) {
        //this will output on the console whenever the method is being used
        console.log("setter method used");
        this._firstName = firstName;   
    }
}
const person1 = new Person('Marko', '2002', 'tennis');

You should see on the console that the setter method was used once. Now try changing the first line of your constructor to this._firstName = firstName;

Upvotes: 1

Related Questions