I have a couple variables that need to have a getter
and setter
. Instead of creating a new class for each of them, I want to create one class, and create instances of that class for the variables.
Here's the code I tried, but I get an error (basically) saying test
is undefined
. What am I dong wrong, and how can I fix this? Also, is it common to do it this way? Am I taking the correct approach?
function GetterSetter( /** Any Value */ value, /** Function */ getter, /** Function */ setter) {
this.set = function(val) {
this.value = val;
typeof setter === 'function' && setter();
console.log('actual setter');
};
this.get = function() {
typeof getter === 'function' && getter();
console.log('actual getter');
return this.value;
};
(typeof value !== 'undefined' && value !== null) && this.set(value);
}
var test = GetterSetter('hello', function() {
console.log('custom getter');
}, function() {
console.log('custom setter');
});
This is the actual error message:
Uncaught TypeError: Cannot read property 'get' of undefined