Encapsulating in JavaScript, does it exist?

前端 未结 4 979
予麋鹿
予麋鹿 2021-01-07 00:03

I have an experience with the C# programming language, but I also have to work with the JS now and it\'s rather new for me.

I have tried to develop a simple class em

4条回答
  •  半阙折子戏
    2021-01-07 01:03

    You can use closures to encapsulate variables.

    function MyObjectFactory() {
      var obj = {},
        count = 0;
    
      obj.getCounter = function () {
        return count;
      };
    
      obj.setCounter = function (val) {
        count = val;
      };
    
      obj.incrementCounter = function () {
        count++;
      };
    
      obj.decrementCount = function () {
        count--;
      };
    
      return obj;  
    }
    

    You can also imitate property getters and setters in generic way.

    function MyOtherObjectFactory() {
      var obj = {}, props = {};
    
      obj.prop = function (name) {
        return props[name];
      };
    
      obj.setProp = function (name, val) {
        props[name] = val;
        // call other functions if you'd like
      };
    
    
      // or even better, have a single function that works getter and setter regarding the params
      obj.autoProp = function () {
        if (arguments[1]) {
          // setter
          props[arguments[0]] = arguments[1]; // do check first argument is a hashable value
        } else if (arguments[0]) {
          // make sure we have a key
          // getter
          return props[arguments[0]];
        }
      }
    }
    

    PS: Please don't set prototype directly, it breaks the prototype chain.

提交回复
热议问题