Problem with code involving getters and setters

javascript

#1

let driverId = {
_name: ‘Cristiano Ronaldo’,
_age: ‘th’,
_countryOfOrigin: ‘Portugal’,
set age(newAge) {
if (typeof newAge === ‘number’) {
this._age = newAge;
} else {
console.log(‘Invalid Input’);
return ‘Invalid Input’;
}
},
set name(newName) {
if (typeof newName !== ‘number’ && this._age > 18) {
console.log(${this._name} is allowed to drive)
return this.name;
} else {
console.log(“You’re not eligible to drive yet.”)
}

}
};
console.log(driverId.name);
I just cant understand why this code returns undefined?


#2

I could be mistaken, but I believe setters and getters are part of a class definition, and not plain objects.


#3

Please can you be a little less technical. I am a 15 year old bio student and just learn coding as a computer hobbyist. :blush::grinning:


#4

Setters do not have returns. They set the instance variable they are attached to.

Rather than using a setter to reveal unrelated information, use a method…

For an example of a class:

class Driver {
    static canDrive(age) {
      return age >= 18
    }
    constructor(name, age) {
        this._name = name;
        this._age = age;
        this.canDrive = Driver.canDrive(age);
    }
    get name() {
      return this._name;
    }
    get age() {
      return this._age;
    }
    set name(newName) {
      this._name = newName;
    }
    set age(newAge) {
      this._age = newAge;
      this.canDrive = Driver.canDrive(newAge);
    }
}

const bob = new Driver("Bob", 16);
console.log(bob.canDrive);    //-> false

const joe = new Driver("Joe", 18);
console.log(joe.canDrive);    //-> true

bob.age = 19;
console.log(bob.canDrive);    //-> true

There are some subtleties to discuss. Play with the REPL, here,

https://repl.it/MQNp

and we can take up any of your questions.


#5

Now to demonstrate what happens when we use class object syntax in a plain object.

const bob = {
    _name: `Bob`,
    _age: 16,
    canDrive: () => this._age >= 18,
    setName: newName => this._name = newName,
    setAge: newAge => this._age = newAge,
    getName: () => this._name,
    getAge: () => this._age,
};

console.log(bob.getName(), bob.getAge(), bob.canDrive());
//->  undefined undefined false

bob.setName(`Bob`);
bob.setAge(19);
console.log(bob.getName(), bob.getAge(), bob.canDrive());
//->  Bob 19 true

Notice that the original values did not register? It’s the underscores that are behind it. Yet once we set the values, they are all good. Note also how the methods are written. A bit different from class syntax.

https://repl.it/MQZI/1


#6

thanks alot. :grinning::hugs:


#7

After all that, I must return to apologize for misinforming you. I’ve given this question some more attention (due to another posted topic) and discovered both my error and why your code did not function . Your object does not have a getter.

let driverId = {
  _name: ‘Cristiano Ronaldo’,
  _age: ‘th’,
  countryOfOrigin: ‘Portugal’,
  set age(newAge) {
    if (typeof newAge === ‘number’) {
      this._age = newAge;
    } else {
      console.log(‘Invalid Input’);
      return ‘Invalid Input’;
    }
  },
  set name(newName) {
    if (typeof newName !== ‘number’ && this._age > 18) {
      console.log(${this._name} is allowed to drive)
    return this.name;
    } else {
      console.log(“You’re not eligible to drive yet.”)
    }
  },
  get age() {
    return this._age;
  },
  get name() {
    return this._name;
  }
};

Above, countryOfOrigin has no setter or getter so needs no _.

Rewriting my earlier example that used methods as properties to use setters and getters…

const bob = {
    _name: `Bob`,
    _age: 16,
    canDrive: function() {
      return this._age >= 18;
    },
    set name (newName) {
      this._name = newName;
    } ,
    set age (newAge) {
      this._age = newAge;
    },
    get name() {
      return this._name
    },
    get age () {
      return this._age;
    },
};

console.log(bob.name, bob.age, bob.canDrive()); 
// Bob 16 false
bob.age = 18;
console.log(bob.name, bob.age, bob.canDrive());
// Bob 18 true

https://repl.it/MQZI/2

Hopefully this gets you safely on your way to better understanding setters and getters. I’m glad I took the time to check for and find my own errors.

Lastly, is the opening post code from an exercise? If so, please post a link to it and I’ll correctly file this topic. Thanks.


#8

So you mean that my code only requires getters and no underscore in the
country OfOrigin key?


#9

Nope, I made it myself after learning the ‘getters and setters’ exercise just to test my understanding.


#10

Correct. The underscore marks (data) that is encapsulated (can only be accessed internally). The outside accesses the data through the getter and setter. During my research I came across a good article which I’ve added to the In Depth subject in the corner bar. Give that a read while you’re studying this topic.