JS: Getters & Setters

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects#Defining_getters_and_setters

by kyllle

HTML

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.6/css/bootstrap.css">
<p>A getter is a method that gets the value of a specific property. A setter is a method that sets the value of a specific property. You can define getters and setters on any predefined core object or user-defined object that supports the addition of new properties. The syntax for defining getters and setters uses the object literal syntax.</p>

SCSS

* {
  -webkit-font-smoothing: antialiased;
}

body {
    padding: 5%;
}

JavaScript

console.clear();

// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects#Defining_getters_and_setters

var obj = {
	int: 0,
    get: function() {
    	return this.int;
    },
    set: function(num) {
    	this.int = num;
    }
}

// Getters
console.log('Get::', obj.get());

// Setters
obj.set(10);
console.log('Set::', obj.int);