0

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

Jessica
  • 9,379
  • 14
  • 65
  • 136

1 Answers1

3
var test = GetterSetter(...);
           ^

You're missing a new here:

var test = new GetterSetter(...);

This means this in GetterSetter is the global window object, not a new instance, and test is the actual return value of GetterSetter (which doesn't return anything, hence undefined).

melpomene
  • 84,125
  • 8
  • 85
  • 148
  • Thanks for the quick answer! (How could I have not seen that? lol) Is that good practice? Is it common to do it? – Jessica Jun 24 '16 at 21:11
  • Is "using the `new` keyword in JS good practice" you mean? Short answer: there's nothing wrong with it, and it's a common paradigm. Long answer: it's another question, which has several answers here: http://stackoverflow.com/questions/383402/is-javascripts-new-keyword-considered-harmful – Assimilater Jun 24 '16 at 21:16
  • @Assimilater I meant is the `GetterSetter` class I made good practice? – Jessica Jun 24 '16 at 21:18