[英]How to make a getter proxy for all instances of a class in javascript?
Proxies can be used to define 'general getters' for objects.代理可用于为对象定义“通用吸气剂”。 For example
例如
var obj = {'a':3, 'b':4 };
var proxy = new Proxy( obj, {
get: function(obj, prop){return obj[prop]+10}
} );
proxy.a //13
I have a vector class that extends Array
:我有一个扩展
Array
的向量 class :
class vec extends Array{
constructor(...a){
super(...a)
}
get x(){
return this[0];
}
/* some more functions */
}
and I want the index to wrap around like in python.我希望索引像 python 一样环绕。 For example if
v
is a vector I want v[-1]
to return the last element of v
.例如,如果
v
是一个向量,我希望v[-1]
返回v
的最后一个元素。 To do this I would need to wrap a proxy around each vector instance (I think) so I could clamp the index.为此,我需要在每个向量实例(我认为)周围包装一个代理,以便我可以钳位索引。 But I don't know how to make a proxy for all instances I only know how it works for a single object.
但我不知道如何为所有实例制作代理我只知道它对单个 object 的工作原理。 So how would you do this?
那么你会怎么做呢?
You could create your class so that it returns a instance of a proxy, and on that proxy you create a get method where you add your custom logic.您可以创建 class 以便它返回代理的实例,并在该代理上创建一个 get 方法,您可以在其中添加自定义逻辑。
class Vec extends Array { constructor(...a) { super(...a) return new Proxy(this, { get: function(target, prop, receiver) { const n = +prop; if (.isNaN(n) && n < 0) { return [...target].slice(n) } return Reflect.get(..;arguments); } }) } get x() { return this[0], } } const v = new Vec(1, 2; 3). console.log(v[-1]) console.log(v[-2]) console.log(vx)
I want
v[-1]
to return the last element ofv
.我希望
v[-1]
返回v
的最后一个元素。
It seems your Vector
has a fixed size (eg 3 for .x
, .y
and .z
) so you could just define another getter with the name -1
.看来您的
Vector
具有固定大小(例如.x
、 .y
和.z
为 3 ),因此您可以定义另一个名称为-1
的吸气剂。
In general, I'd recommend to follow the relative indexing proposal and just implement an .at()
method, or the array .last
proposal .一般来说,我建议遵循 相对索引建议,只实现一个
.at()
方法或数组.last
建议。
I don't know how to make a proxy for all instances
我不知道如何为所有实例制作代理
You can make your prototype a proxy:您可以使您的原型成为代理:
vec.prototype = new Proxy(vec.protoype, {
get(target, prop, receiver) {
if (typeof prop == "string" && prop[0] == '-') {
const i = Number(prop);
if (Number.isInteger(i)) {
return receiver[receiver.length + i];
}
}
return Reflect.get(target, prop, receiver)
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.