Make a property either invokable or not

删除回忆录丶 提交于 2020-01-04 02:43:23

问题


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


回答1:


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




回答2:


You can use ES6 syntax:

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

  get string(){
    return this.someString;
  }

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


来源:https://stackoverflow.com/questions/43902656/make-a-property-either-invokable-or-not

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!