JS Setters/Getters
Using JS setters/getters inside of a object constructor pattern. We expose a hidden scoped variable as a property of the object (in this case, the variable `name` is exposed as a property `name). However, we can modify the value of the variable before returning it as an object property, and even prevent setting the value of the variable by throwing an error in the setter.
by thirdender
JavaScript
var output = [];
var Asdf = function(name) {
var name = name;
Object.defineProperties(this, {
name: {
get: function() {
return name;
},
set: function(x) {
throw new Error('Cannot set property "name" of object Asdf');
}
}
});
};
var asdf = new Asdf('Qwerty')
uiop = new Asdf('Uiop');
output.push(asdf.name);
output.push(uiop.name);
$('body').append(output.join('<br />'));
asdf.name = 'Testing'; // See console for thrown error