这是我尝试使用的代码(注意:这不是解决方案):
// define main object
class MyObject {}
// set proxy of Object's prototype as prototype of main object
Object.setPrototypeOf( MyObject.prototype, new Proxy( Object.prototype, {
// implement new get behavior
get( trapTarget, key, reciever ){
// throw error if unexistansible variable is tried to be called
if ( ! key in trapTarget )
throw new SyntaxError( 'message' );
return Reflect.get( trapTarget, key, reciever );
}
}));
// define new child class
class MyChildObject extends MyObject {}
let child = new MyChildObject();
由于MyObject.protototype代理被称为对象的原型,因此我们无法从继承的实例中获取任何属性。
我的代码如何工作:
child.unexistansibleVar
方法时,get()
将被代理捕获child.prototype
始终为trapTarget
,所以我无法实现Object.prototype
,因此将尝试在此处找到所有键它应该如何工作:
child.unexistansibleVar
child
并检查if ( ! key in child )
我的问题:
child
?class MainClass {
constructor() {
return new Proxy( this, {
get( trapTarget, key, reciever ) {
if ( ! ( key in trapTarget) )
throw new SyntaxError( 'msg' );
return Reflect.get( trapTarget, key );
}
});
}
}
class ChildClass extends MainClass {}
let child = new ChildClass();
child.name = 'child object';
console.log( child.name ); // 'child object'
console.log( child.some ); // error 'msg'