Ecmascript 6:如何实现代理get()继承酶?

问题描述 投票:0回答:1

这是我尝试使用的代码(注意:这不是解决方案):

// 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
  • 方法get()将被代理捕获
  • 代理应达到child并检查if ( ! key in child )

我的问题:

  • 是否可以通过代理接收child
  • 也许有其他方法可以实现我的目标?
javascript inheritance proxy ecmascript-6 prototypejs
1个回答
0
投票
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'
© www.soinside.com 2019 - 2024. All rights reserved.