23

I'm using babelify version 6.3.0 set to stage 0. ES6 / ES7 are working great. However when I try to use Javascript's proxy functionality:

set product(product={}) {
  this._product = new Proxy({}, {})
}

I get:

ReferenceError: Can't find variable: Proxy

Any ideas?

user3840170
  • 26,597
  • 4
  • 30
  • 62
Allyl Isocyanate
  • 13,306
  • 17
  • 79
  • 130
  • Possible duplicate of [Reference Error: Proxy is Not Defined](http://stackoverflow.com/questions/31348985/reference-error-proxy-is-not-defined) – John Slegers Feb 24 '16 at 00:32

3 Answers3

34

From the Babel website:

Due to the limitations of ES5, Proxies cannot be transpiled or polyfilled. See support in various JavaScript engines.

Mike Cluck
  • 31,869
  • 13
  • 80
  • 91
  • 3
    Well, that's unfortunate. The Chrome team released a polyfill: https://github.com/GoogleChrome/proxy-polyfill, in case that helps anyone. – Bryce Johnson Jul 06 '16 at 22:19
  • 3
    Apparently is *is* doable in ES5, according to this package: https://www.npmjs.com/package/babel-plugin-proxy – trusktr Jul 14 '16 at 11:08
  • 7
    @trusktr Technically speaking, yes but as the creators said "[i]t is not suitable for production environments because performance impact is huge." They replace every single property access with a call to a special function. – Mike Cluck Jul 14 '16 at 16:21
  • 1
    @BryceJohnson That polyfill does not allow dynamic keys. It seals your object. – SCLeo May 26 '17 at 13:59
6

You cannot proxy a full object with all the traps but you can create proxied properties for get and set at least.

var proxy = {}

Object.defineProperty(proxy, 'a', {
  get: function() { return bValue; },
  set: function(newValue) { bValue = newValue; }
});

You can even wrap it around a method

function proxyVar(obj, key, initVal) {
  Object.defineProperty(obj, key, {
    get: function() { return bValue*2; },
    set: function(newValue) { bValue = newValue; }
    value: initVal
  });
}

And then:

var proxy = {}

proxyVar(proxy, 'a', 10)

console.log(proxy.a) // prints 20
proxy.a = 20
console.log(proxy.a) // prints 40
DiegoRBaquero
  • 1,208
  • 10
  • 14
2

Babel translates ES6/ES7 code (assuming you've connected the appropriate presets) into valid ES5 code.

I'm afraid that there's no way to express ES6 proxies via ES5 syntax.

You can see that proxies don't nave any equivalent on es6-features site. There's also a warning about it in the bottom of 'proxies' section of Babel docs.

everyonesdesign
  • 356
  • 2
  • 9