Showing posts with label Advanced-getSet. Show all posts
Showing posts with label Advanced-getSet. Show all posts

Friday, May 11, 2018

Setter and Getter compatability

The below is another way of setting and getting property values and its really a very compatible mode.

Simple Example :


1
2
3
4
5
6
7
8
function User(name, age) {
  this.name = name;
  this.age = age;
}

let john = new User("Test", 25);

alert( john.age ); // 25

Explanation:

1. Line no 6 we are creating value for name and age property.  So the name and age will be assigned  (setter).

2. In line no 8, we are getting age value.

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