3

I want to make a property either invokable or not. So for example:

function Test () {
  var obj = { someString: 'here is text' };

  Object.defineProperty(obj, 'string', {
    get: function() {
      return obj.someString;
    },
    set: function() {
      return function(val) {
        obj.someString = val;
      }
    }
  });

  return obj;
}

var test = new Test();

That way I could do:

test.string // initially returns 'here is text'

test.string('new text here') // sets obj.someString to 'new text here'

test.string // returns 'next text here'

The code above does not currently function the way I want it to. Is there anyway to do something like this in JavaScript? Either using Object.defineProperty or not

georgej
  • 3,041
  • 6
  • 24
  • 46

2 Answers2

0

I'm not sure that it's possible to do that. Instead, you could do conditional for if a function parameter is set and if it's not have the function read the property:

function Test () {
  var obj = { 
    someString: 'here is text',
    string: function(val) {
      if(val == undefined) { // If the val parameter was not defined
        return this.someString; // Just return the property someString
      } else { // Otherwise, 
        this.someString = val; 
      }
    }
  };
  return obj;
}

var Tmp = new Test();
console.log(Tmp.string()); // This outputs 'here is text'
Tmp.string('New text!'); // This sets someString to 'New Text!'
console.log(Tmp.string()); // This outputs 'New Text!'

The main difference between this and what you wanted is that instead of caling Tmp.string to retrieve the value, you're calling Tmp.string().

Here's my jsfiddle

D. R.
  • 324
  • 1
  • 10
0

You can use ES6 syntax:

class Test{
  constructor(){
    this.someString = "here is text";
  }

  get string(){
    return this.someString;
  }

  set string(val){
    this.someString = val
  }
}
andrey
  • 1,867
  • 3
  • 21
  • 34