New getters and setters in Es6 JavaScript.

This is a simple example on how to implemet getters and setters in Es6 JavaScript.


class Point {
constructor(x, y) {
this._x = x;
this._y = y;
}
get X() {
return this._x;
}
get Y() {
return this._y;
}
set X(x) {
this._x = x;
}
set Y(y) {
this._y = y;
}
}

var p = new Point(10, 20);

p.X;

And now how to do it without class system.


function Point(x, y) {
this._x = x;
this._y = y;

this.getX = function() {
return this._x;
};

this.getY = function() {
return this._y;
};

this.setX = function(x) {
this._x = x;
};

this.setY = function(y) {
this._y = y;
};
}

var p = new Point(10, 20);

p.getX();

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s