[英]How to call an object method by Proxy in Javascript?
I have the class:我有课:
class Course {
constructor(name) {
this._name = name;
}
getName() {
return this._name;
}
}
I want to create a proxy around class Course, that will return only non-private fields and methods:我想围绕类 Course 创建一个代理,它将只返回非私有字段和方法:
const handlers = {
get: (target, prop, reciever) => {
if (prop in reciever && prop[0] !== '_' ) {
if (typeof reciever[prop] === 'function') {
return reciever[prop].apply(reciever);
} else {
return reciever[prop];
}
} else {
throw new Error('problem');
}
}
}
const protect = (obj) => {
return new Proxy(obj, handlers);
}
But when i call object method:但是当我调用对象方法时:
const protectedCourse = protect(new Course('Test'));
console.log(protectedCourse.getName()); // The expected result is - "Test"
I got the error:我得到了错误:
if (prop in reciever && prop[0] !== '_' ) {
^
RangeError: Maximum call stack size exceeded
at Object.get (file:///usr/src/app/protect.js:37:5)
at Object.get (file:///usr/src/app/protect.js:38:26)
at Object.get (file:///usr/src/app/protect.js:38:26)
at Object.get (file:///usr/src/app/protect.js:38:26)
at Object.get (file:///usr/src/app/protect.js:38:26)
at Object.get (file:///usr/src/app/protect.js:38:26)
at Object.get (file:///usr/src/app/protect.js:38:26)
at Object.get (file:///usr/src/app/protect.js:38:26)
at Object.get (file:///usr/src/app/protect.js:38:26)
at Object.get (file:///usr/src/app/protect.js:38:26)
How to call object method without infinity recursion in the handler of Proxy?如何在代理的处理程序中调用对象方法而无需无限递归?
You should access the property on target
, which is the original object, instead of receiver
which is the Proxy
.您应该访问
target
上的属性,它是原始对象,而不是receiver
,它是Proxy
。 Additionally, use bind
instead of apply
or call
to return a function with the this
value set.此外,使用
bind
而不是apply
或call
来返回设置了this
值的函数。
Note that what you are trying to achieve with a Proxy
can be done with private class fields .请注意,您尝试使用
Proxy
实现的目标可以使用私有类字段来完成。
class Course { constructor(name) { this._name = name; } getName() { return this._name; } } const handlers = { get: (target, prop, receiver) => { if (prop in target && prop[0] !== '_') { if (typeof target[prop] === 'function') { return target[prop].bind(target); } else { return target[prop]; } } else { throw new Error('problem'); } } } const protect = (obj) => { return new Proxy(obj, handlers); } const protectedCourse = protect(new Course('Test')); console.log(protectedCourse.getName());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.