John Preston
John Preston

Reputation: 785

Javascript Getters And Setters

Can somebody please tell me about getters and setters in javascript? What are actually getters and setters? Where we can use them? What are the benefits of using them?

Upvotes: 3

Views: 735

Answers (3)

BalaKrishnan웃
BalaKrishnan웃

Reputation: 4557

Getter and setter both are functions.

Getter will call when a value is retrieve from variable/object(which has Getter) Getter function must return value.

var i=count;

if the count's getter is already defined, it will call.

Setter will call when a value is assign to a variable/object(which has Setter)

count=10

if the count's setter is already defined, it will call.

take a look at this example so that you can easily understand the use of Getter and setter

How to get notified within an object when one of that object’s property changes?

Upvotes: 3

RobG
RobG

Reputation: 147343

You might use a getter or setter if you want to put conditions on the setting/getting of a property value, or have something else happen when they are set/got.

You may also find the MDN documentation on the Mozilla proprietary set and get operators helpful:

  1. Working with objects—Defining getters and setters
  2. set operator
  3. get operator

Upvotes: 3

bryan.blackbee
bryan.blackbee

Reputation: 1954

Generally, getters and setters are used for Object Oriented Programming in Javascript.

Typically, in a class, there are some attributes, a constructor, getters and setters.

Attributes represent properties of a class

Constructor creates an instance of a class

Getters help to retrieve the attributes of an object

var name = cat.getName();

Setters help to manipulate the attributes of an object.

eg. cat.setName('Kathreen');

Read more about OOP in Javascript to find out more.

Upvotes: 3

Related Questions