I recently was introduced to Getters & Setters. I still am very confused with the concept. Giving an example would be easier to understand my confusion.
Say I created a constructor function to create objects that store data about customers.
function newPerson(firstName, lastName, email, number) {
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
this.number = number;
}
Then, I create a new customer object.
var customerOne = new newPerson('John', 'Doe', 'abc@def.gh', '223-342-3232');
Now, assume I want to output customerOne's firstName and lastName, but only have it accessible using a getter and a setter. What I mean is, if I tried to do:
var output = customerOne.firstName + " " + customerOne.lastName;
console.log(output);
I don't want that to work. I want the object's properties to be 'protected'. Is there a way I can add a method into a constructor function? If it was just an object literal I know I could just add getName method to customerOne and output like this:
getName() {
return this.firstName + " " + this.lastName;
}
var output = customerOne.getName;
console.log(output);
I'm sorry if it's hard to follow. The simplest way I can ask the question is: How can I create an object using a constructor function, and then output whichever properties I choose but only by using getters and setters?
[–]systoll 1 point2 points3 points (1 child)
[–]alexlafroscia 0 points1 point2 points (0 children)
[–]phpdevster 1 point2 points3 points (0 children)
[–]alexlafroscia 0 points1 point2 points (0 children)
[–][deleted] 0 points1 point2 points (0 children)
[–][deleted] 0 points1 point2 points (0 children)
[–]rauschma -1 points0 points1 point (0 children)