Ash*_*ain 5 javascript proxies ecmascript-6
Javascript的新代理功能提供了一些有趣的调试功能.例如get,如果您访问未定义的属性,则可以通过将其置于具有处理程序的代理服务器来"保护"对象.这有助于捕捉拼写错误和其他类型的错误.
这可以使用这样的东西:
class Something {
constructor()
{
this.foo = "bar";
allObjects.push(this);
}
};
function defend(o)
{
return new Proxy(o, DebugCheckHandler);
};
let rawSomething = new Something();
let defendedSomething = defend(rawSomething);
Run Code Online (Sandbox Code Playgroud)
代码可以勤勉地编写,只处理defendedSomething.但是在此示例中,Something构造函数传递this到其他位置(to allObjects).这最终会产生与使用两者rawSomething和defendedSomething跨代码库相同的效果.
然后问题出现在代理引用不等于其原始引用的事实上,因为rawSomething !== defendedSomething.例如,allObjects.includes(defendedSomething)如果包含,则返回false rawSomething,因为includes会进行严格===检查.
有没有一种很好的方法可以解决这个问题,而无需对代码进行太多更改?
new您可以:
prototype。this值传递的构造函数。function Something() {
this.foo = "bar";
allObjects.push(this);
}
function defendIntanceOf(C) {
var p = new Proxy(Object.create(C.prototype), DebugCheckHandler);
C.call(p);
return p;
};
let defendedSomething = defendIntanceOf(Something);
Run Code Online (Sandbox Code Playgroud)
注意我使用函数语法而不是类语法,以便能够使用Function.call自定义this值调用 [[Call]]。
| 归档时间: |
|
| 查看次数: |
785 次 |
| 最近记录: |