【问题标题】:Ecmascript 6: how to implement proxy get() inheritase?Ecmascript 6:如何实现代理 get() 继承?
【发布时间】:2018-03-01 03:46:33
【问题描述】:

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

// 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 代理引用了 Object 的原型,我们无法从继承的实例中获取任何属性。

我的代码是如何工作的:

  • 当我们调用 child.unexistansibleVar 方法时,get() 将被代理捕获
  • 我无法实现child.prototype,由于代理的trapTarget 将始终是Object.prototype,因此将尝试在那里找到所有密钥

它应该如何工作:

  • 我们打电话给child.unexistansibleVar
  • get() 方法将被代理捕获
  • 代理应该达到child并检查if ( ! key in child )

我的问题:

  • 是否可以在代理中接收child
  • 可能有什么不同的方法可以实现我的目标?

【问题讨论】:

  • 代理会导致间接影响性能。您应该只在特殊情况下使用此技术。相反,应用像 flow 这样的静态类型检查器来获得类型安全的鸭子类型。

标签: javascript inheritance proxy ecmascript-6 prototypejs


【解决方案1】:
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'

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-26
    • 2013-07-25
    相关资源
    最近更新 更多