我当时想成为一名偷偷摸摸的开发人员,但是我确实迷上了ES6 Proxies。基本上,我想从我编写的另一个类中捕获属性中的任何获取或设置,并确保它们存储在对象之外的其他位置。看起来像这样:
'use strict'
class MyObject()
{
superAwesomeFunction(){//super awesome code goes here}
}
const myProxyObject = new Proxy(MyObject, {
get: function(target, name, receiver)
{
if([CONDITIONS THAT MEET MY DEMANDS])
{
// deliver property values if they are
// my super cool database (if they exist)
}
// else just ya know, forward it to the actual MyObject
// property, if it's an actual property on MyObject
return target[name];
},
set: function(target, name, value)
{
if([CONDITIONS THAT MEET MY DEMANDS])
{
// set property values if they are
// to super cool database
}
else
{
// just set the value to the property, which
// gets created if it doesn't exist (WHICH IS SO COOL)
target[name] = value;
}
return true;
}
好吧,这很酷?您可以执行以下操作:
// property that doesn't exist (yet)
console.log(myProxyObject.wholivesinapineappleunderthesea);
// but wait for it...
myProxyObject.wholivesinapineappleunderthesea = 'spongebob';
// bam! now it exists on the object, AND lives in my DB!
console.log(myProxyObject.wholivesinapineappleunderthesea);
哪怕花很多时间做些笨拙的事情,我也无法解释这让我感到多么幸福。但是,这有一个问题。还记得我放入MyObject()中的superAwesomeFunction()吗?好吧,每当我现在尝试调用它时,ES6都会给我带来这样的悲伤:
myProxyObject.superAwesomeFunction不是函数
ES6坐在LIES的宝座上!完全在那里吗?好的,我可以确定自己捕获了错误,因为在调试时,我看到Proxy的get部分实际上正在接管superAwesomeFunction调用(这很有意义,因为superAwesomeFunction是包含函数()的属性{ })
这是我的问题:是否有人知道有什么解决方案可以让我对飞行属性保持可笑,并仍然调用我的superAwesomeFunction()?是申请陷阱吗?
最佳答案
那里是一个小语法错误……您是将代理包装在原始类(而不是对象)周围。
尝试:
const myProxyObject = new Proxy(new MyObject(), { ... });
没关系例如:
> class Blah {
... run() {
..... console.log('yay')
..... }
... }
[Function: blah]
> myProx = new Proxy(new Blah(), {});
blah {}
> myProx.run()
yay