Javascript Getters And Setters

2019-07-20 05:47发布

问题:

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?

回答1:

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.



回答2:

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?



回答3:

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