如何在构造函数中包装使用 Proxy 构造的对象?
How to wrap object being constructed with Proxy inside constructor?
我知道 Proxy
可用于更改对象级行为,例如括号表示法 get 和 set。我能找到的所有示例都显示构造一个对象,然后用 Proxy
调用包装它。有没有一种方法可以使用 ES6 class 构造函数符号来定义 class Foo
,这样构造函数返回的对象已经包含在 Proxy
中,而不是调用者构造函数还必须单独调用 Proxy
?
提前致谢。
据我所知:没有,但您可以在之后设置 prototype
。像这样:
class Thing {
constructor() {
// ...
}
}
Thing.prototype = new Proxy(Thing.prototype, {
get(target, name) {
// ...
}
});
如果我正确理解你的问题,你想做的是在构造函数中 return 像这样的新代理:
class MyClass {
constructor() {
return new Proxy(this, {
// Proxy settings here
})
}
}
在此示例中,我们创建一个新的 class,然后调用一些属性。然后代理将只打印出为简单起见调用的属性。
class MyClass {
constructor() {
return new Proxy(this, {
get: (target, key) => {
console.log('I am the key: ' + key)
return Reflect.get(target, key)
}
})
}
}
let c = new MyClass
c.awesome
c.billy
c.superTroopers
if (c instanceof MyClass) {
console.log('I am an instance of MyClass')
} else {
console.log('I am not an instance of MyClass')
}
我知道 Proxy
可用于更改对象级行为,例如括号表示法 get 和 set。我能找到的所有示例都显示构造一个对象,然后用 Proxy
调用包装它。有没有一种方法可以使用 ES6 class 构造函数符号来定义 class Foo
,这样构造函数返回的对象已经包含在 Proxy
中,而不是调用者构造函数还必须单独调用 Proxy
?
提前致谢。
据我所知:没有,但您可以在之后设置 prototype
。像这样:
class Thing {
constructor() {
// ...
}
}
Thing.prototype = new Proxy(Thing.prototype, {
get(target, name) {
// ...
}
});
如果我正确理解你的问题,你想做的是在构造函数中 return 像这样的新代理:
class MyClass {
constructor() {
return new Proxy(this, {
// Proxy settings here
})
}
}
在此示例中,我们创建一个新的 class,然后调用一些属性。然后代理将只打印出为简单起见调用的属性。
class MyClass {
constructor() {
return new Proxy(this, {
get: (target, key) => {
console.log('I am the key: ' + key)
return Reflect.get(target, key)
}
})
}
}
let c = new MyClass
c.awesome
c.billy
c.superTroopers
if (c instanceof MyClass) {
console.log('I am an instance of MyClass')
} else {
console.log('I am not an instance of MyClass')
}