Make the property either invokable or not

I want to make the property invokable or not. 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();

      

This 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'

At the moment the code is not working the way I want. Is there a way to do something like this in JavaScript? Either using Object.defineProperty

or not

+3


source to share


2 answers


I'm not sure if this is possible. Instead, you can do conditionally if a function parameter is set, and if it doesn't have a 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 calling Tmp.string to get the value, you are calling Tmp.string ().

Here's my jsfiddle

0


source


ES6 syntax can be used:



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

  get string(){
    return this.someString;
  }

  set string(val){
    this.someString = val
  }
}

      

0


source







All Articles