Javascript singleton,如何更新这个变量?

时间:2015-11-05 02:49:08

标签: javascript javascript-objects

快速提问。假设我有这个对象:

var door = (function(){
    var state = "closed";

    function doSomething(){
      //do something here
      state = "open";
    }

    return {
        activate: function() {
           doSomething();
        },
        doorState: state
    }
})();

现在,如果我这样做:door.activate() door.doorState已“关闭”。我可以这样做:

doorState: function(){state}

但这需要我door.doorState()

我希望能够更新对象的状态而不是调用函数。

如何?

1 个答案:

答案 0 :(得分:1)

问题是你只是更新局部变量,但它不会更新doorState属性的值

您可以更新返回对象的属性



var door = (function() {

  function doSomething() {
    //do something here
    obj.doorState = "open";
  }

  var obj = {
    activate: function() {
      doSomething();
    },
    doorState: "closed"
  }
  return obj;
})();

snippet.log('before: ' + door.doorState);
door.activate();
snippet.log('after: ' + door.doorState);

<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
&#13;
&#13;
&#13;

使用getter语法 - supported in IE9+

&#13;
&#13;
var door = (function() {
  var door = 'closed';

  function doSomething() {
    //do something here
    door = "open";
  }

  return {
    activate: function() {
      doSomething();
    },
    get doorState() {
      return door;
    }
  }
})();

snippet.log('before: ' + door.doorState);
door.activate();
snippet.log('after: ' + door.doorState);
&#13;
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
&#13;
&#13;
&#13;