proxy 

Send to Kindle
home » snippets » javascript » es6 » proxy



Snippets

// polyfill the global ES6 Proxy object.
var Reflect = require('harmony-reflect');

function SealConstructor(obj) {
  return Proxy(obj, __ProxyHandlerForSeal);
}

var __ProxyHandlerForSeal = {
  get: function proxyGetIfDefined(obj, name) {
    //console.log("GET:", arguments);  // keep commented else we have an infinite loop.
    var result = obj[name];
    // whitelist the names "inspect" and "toJSON" else console.log(proxy_obj) will throw the error here.
    if (result === undefined && (name !== "inspect" && name !== "toJSON")) {
      throw Error(util.format(
          "Reading undefined property '%s' on instance of type '%s'. instance='%s'",
          name, __getTypeNameOf(obj), obj));
    }
    return result;
  },
  set: function proxySetIfExists(obj, name, value) {
    //console.log("SET:", arguments);  // keep commented else we have an infinite loop.
    var result = obj[name];
    if (result === undefined && (name !== "inspect" && name !== "toJSON")) {
      throw Error(util.format(
          "Setting undefined property '%s' on instance of type '%s'. instance='%s'",
          name, __getTypeNameOf(obj), obj));
    }
    obj[name] = value;
    return obj;
  },
  construct: function proxyConstruct(target, args) {
    return SealObject(Reflect.construct(target, args));
  }
};

function __getTypeNameOf(obj) {
  var name = typeof obj;
  if (name !== "object") {
    return name;
  }
  var constructor = obj.constructor;
  if (constructor == null) {
    return name;
  }
  var constructorName = constructor.name;
  if (constructorName != null) {
    return constructorName;
  }
  return name;
}

NestedParserState = SealConstructor(NestedParserState);
InterpolationParts = SealConstructor(InterpolationParts);
MessageFormatParser = SealConstructor(MessageFormatParser);