javascript 在Javascript中生成可覆盖的getter和setter

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了javascript 在Javascript中生成可覆盖的getter和setter相关的知识,希望对你有一定的参考价值。

// see blog post: http://www.hiddentao.com/archives/2013/07/08/generate-overridable-getters-and-setters-in-javascript/
Function.prototype.generateProperty = function(name, options) {
    // internal member variable name
    var privateName = '__' + name;

    options = options || {};
    options.get = ('undefined' === typeof options.get ? true : options.get );
    options.set = ('undefined' === typeof options.set ? true : options.set );

    // pre-initialise the internal variable?
    if (options.defaultValue) {
      this.prototype[privateName] = options.defaultValue;
    }

    var definePropOptions = {},
      getterName = '__get_' + name,
      setterName = '__set_' + name;

    // generate the getter
    if(true === options.get) {
      this.prototype[getterName] = function() {
        return this[privateName];
      };
    }
    // use custom getter
    else if (options.get) {
      this.prototype[getterName] = options.get;
    }
    // disable getter
    else {
      this.prototype[getterName] = function() {
        throw new Error('Cannot get: ' + name);
      }
    }

    definePropOptions.get = function() {
      return this[getterName].call(this);
    };

    // generate the setter
    if(true === options.set) {
      this.prototype[setterName] = function(val) {
        this[privateName] = val;
      };
    }
    // use custom setter
    else if (options.set) {
      this.prototype[setterName] = options.set;
    }
    // disable setter
    else {
      this.prototype[setterName] = function() {
        throw new Error('Cannot set: ' + name)
      };
    }

    definePropOptions.set = function(val) {
      this[setterName].call(this, val);
    };

    // do it!
    Object.defineProperty(this.prototype, name, definePropOptions);
  };

以上是关于javascript 在Javascript中生成可覆盖的getter和setter的主要内容,如果未能解决你的问题,请参考以下文章

在javascript中生成随机整数的最快方法是啥?

在javascript中生成随机颜色的最佳方法? [关闭]

javascript 在Javascript中生成可覆盖的getter和setter

Javascript - 在单个数组中生成所有元素组合(成对)

在javascript中的画布中生成随机图像

从 Django 模型中生成 JavaScript 对象