Javascript Proxy support in Babel

一世执手 提交于 2019-12-18 12:15:46

问题


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?


回答1:


From the Babel website:

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




回答2:


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



回答3:


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.



来源:https://stackoverflow.com/questions/35025204/javascript-proxy-support-in-babel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!