3

我想让一个属性要么可调用,要么不可调用。例如:

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();

这样我就可以做到:

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'

上面的代码目前没有按照我想要的方式运行。无论如何在JavaScript中做这样的事情吗?使用Object.defineProperty或不使用

4

2 回答 2

0

我不确定是否可以这样做。相反,如果设置了函数参数并且没有函数读取属性,您可以做条件:

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

这与您想要的主要区别在于,您调用的是 Tmp.string(),而不是调用 Tmp.string 来检索值。

这是我的jsfiddle

于 2017-05-10T21:32:21.457 回答
0

您可以使用 ES6 语法:

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

  get string(){
    return this.someString;
  }

  set string(val){
    this.someString = val
  }
}
于 2017-05-10T21:53:24.627 回答