Getters and Setters in JavaScript

Prototype Objects

 
function Die() {
  // this.faceValue is not necessary but common practice to keep track of the properties of an object
    this.faceValue; 
}

Die.prototype.roll = function() {
  this.faceValue = Math.floor(Math.random() * 6) +1;
};

var die1 = new Die();
var die2 = new Die();
die1.roll();
die2.roll();


console.log(die1.faceValue);
console.log(die2.faceValue);

As soon as you create an object the objects protptype gets created as well, which is shared for each instance(die1 and die2) through the reference __proto__ which refers to the constructor’s(Die) prototype.

Issues with global properties

A public property can set to whatever value

Solution: The property(faceValue) should get incapsulated.

Private and Public members.

Private members can call properties and methods that can’t get accessed outside the construcor function.

Private members gets created by the constructor.
The parameters of the constructor
Members(properties and methods) defined with var inside the constructor will be private.

You use getters and setters to access private properties.

properties that have this will be public…

 
function Foo(param) {
	this.parameter = param; //public
	var secret = 42; // private

	var bar = function() { //private
	     return "forty-two";
    };
}
var foo = new Foo(42);

console.log(foo.parameter); // 42
console.log(foo.secret); // undefined
console.log(foo.bar()); // error

To access these private properties we would need to create a interface thats called Getters and Setters.

If we go back to our dice and makes the property faceValue private with a getter and setter interface to get access to it. We also gonna make sure the input that gets sent in is a value between 1 and 6. Private properties is written with a underscore before the name:

 

function Die() {
   var _faceValue;

Object.defineProperty(this, "faceValue", {
	get: function() {
	return _faceValue;
},
set: function(value) {
	var intValue = parseInt(value, 10);
	if (isNaN(intValue) || intValue < 1 || intValue > 6) {
	throw new Error("faceValue must be between 1 and 6");
}
	_faceValue = value;
     }
  
    });
}

Die.prototype.roll = function() {
  this.faceValue = Math.floor(Math.random() * 6) +1;
}; 

var die1 = new Die();
die1.roll();


die1.faceValue = 2;
console.log(die1.faceValue); // 2

die1.faceValue = 7;
console.log(die1.faceValue); // “error” Error: faceValue must be between 1 and 6

This is powerful as outside the function we cant edit whats going to happend to the facevalue of the object.

If you only want a read only property you don’t need the set function only the get function.

Add your comment