Search This Blog

2021/01/01

Getter & Setter in Javascript:

Es6 has functionality define property getter & setter.

Lets us see how we can do it.


Here is our code


let Person =

{

firstName:"sangram",

lastName:"desai",


get fullName()

{

return `${this.firstName} ${this.lastName}`;

},


set fullName(val)

{

let parts = val.split(' ');

this.firstName = parts[0];

this.lastName = parts[1];

}

};


console.log(Person.fullName);

Person.fullName = "Saurabh Ganguli"

console.log(Person.fullName);

 

Output:

sangram desai
Saurabh Ganguli

We created getter property fullName as follows


get fullName()

{

return `${this.firstName} ${this.lastName}`;

}


while setter fullname is defined as follows


set fullName(val)

{

let parts = val.split(' ');

this.firstName = parts[0];

this.lastName = parts[1];

}


we can access fullName as Person.fullName .

To set fullName a value we can do following

Person.fullName = "Saurabh Ganguli".

No comments:

Post a Comment