-2

for example:

var person = {
  firstName: "John",
  lastName : "Doe",
  language : "",
  set lang(lang) {
  this.language = lang.toUpperCase();
}
};

person.lang = "en";
console.log(person.language)

var person1 = {
 firstName: "John",
 lastName : "Doe",
 language : function(a){return a.toUpperCase()}
};
console.log(person1.language('en'))

this looks exactly the same and the method mode has less written so why should i use setters?

ibrahim mahrir
  • 31,174
  • 5
  • 48
  • 73
  • 2
    How does it look exactly the same? One is used like a property assignment, and one is called like a function. Also, the two examples aren't even doing the same thing. – ibrahim mahrir Dec 06 '20 at 20:43
  • look at this post https://stackoverflow.com/questions/1568091/why-use-getters-and-setters-accessors – Sarabadu Dec 06 '20 at 20:45
  • Does this answer your question? [Why use getters and setters in JavaScript?](https://stackoverflow.com/questions/42342623/why-use-getters-and-setters-in-javascript) – Sarabadu Dec 06 '20 at 20:45

1 Answers1

0

Along with getter methods, we can also create setter methods which reassign values of existing properties within an object. An example of a setter method:

const person = {
  _age: 37,
  set age(newAge){
    if (typeof newAge === 'number'){
      this._age = newAge;
    } else {
      console.log('You must assign a number to age');
    }
  }
};

Notice that in the example above:

  • We can perform a check for what value is being assigned to this._age.
  • When we use the setter method, only values that are numbers will reassign this._age
  • There are different outputs depending on what values are used to reassign this._age.

Then to use the setter method:

    person.age = 40;
    console.log(person._age); // Logs: 40
    person.age = '40';        // Logs: You must assign a number to age

Setter methods like age do not need to be called with a set of parentheses. Syntactically, it looks like we’re reassigning the value of a property.

Like getter methods, there are similar advantages to using setter methods that include checking input, performing actions on properties, and displaying a clear intention for how the object is supposed to be used. Nonetheless, even with a setter method, it is still possible to directly reassign properties. For example, in the example above, we can still set ._age directly:

person._age = 'forty-five'
console.log(person._age); // Prints forty-five
sonEtLumiere
  • 4,461
  • 3
  • 8
  • 35