Friday, May 11, 2018

Getter and Setter with Javascript Property

Below is the code how JS code getter and setter should be,


1
2
3
4
5
6
7
8
9
let obj = {
  get propName() {
    // getter, the code executed on getting obj.propName
  },

  set propName(value) {
    // setter, the code executed on setting obj.propName = value
  }
};

Line no 2 and 6 get and set is keyword and propName is your property name to set and get value.

Example:


1
 2
 3
 4
 5
 6
 7
 8
 9
10
let user = {
  name: "FirstName",
  surname: "LastName",

  get fullName() {
    return `${this.name} ${this.surname}`;
  }
};

alert(user.fullName); // FirstName LastName

Explanation:

1. line no 1 user is an object which have name and surname property.

2. Through line no 10, when you call alert(user.fullName) control will be moved to line no 5 and it will be executed.

3. So line no 6 will return the result your user object property with the help of "this".

Example II:


1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
let user = {
  name: "First",
  surname: "Second",

  get fullName() {
    return `${this.name} ${this.surname}`;
  },

  set fullName(value) {
    [this.name, this.surname] = value.split(" ");
  }
};

// set fullName is executed with the given value.
user.fullName = "Third Fourth";

alert(user.name); //Third
alert(user.surname);// Fourth





No comments:

Post a Comment