【问题标题】:TypeError when trying to Proxy a ES6 class constructor尝试代理 ES6 类构造函数时出现 TypeError
【发布时间】:2017-03-29 21:24:30
【问题描述】:

我正在尝试代理一个 ES6 构造函数(主要是尝试模拟 Python 的描述符以获得乐趣和学习):

class _Record {
    constructor(data) {
        this._data = data;
    }
}

const constrProxyHandlers = {
    construct: function(target, args, cstr) {
        let instProxyHandler = {
            get: (target, prop) => {
                if(prop in target._data) { return target._data[prop] }
                return target[prop]
            },
            set: (target, prop, val) => {
                if(prop in target._data) {
                    target._data[prop] = val;
                } else {
                    target[prop] = val;
                }
                return true
            }
        }
        
        let obj = Object.create(cstr.prototype)
        cstr.apply(obj, args)
        return new Proxy(obj, instProxyHandler)
    }
}

const Record = new Proxy(_Record, constrProxyHandlers)

let rec = new Record({name: 'Vic', age: 25})
console.log([rec.name, rec.age])
rec.name = 'Viktor'
console.log(rec)

如果你运行这个 sn-p,你会得到这个错误:

cstr.apply(obj, args)

TypeError: Class constructor _Record cannot be invoked without 'new'

如果我将cstr.apply 替换为new cstr,构造函数会很快耗尽堆栈(显然会进入无限递归)。

如果我将_Record 类替换为函数(例如,通过 Babel 转译的 would work),这工作。我可以让它与原生 ES6 一起工作吗?

谢谢。

P。 S. 如果重要的话,我目前正在 Node 7.7.4 上检查这些 sn-ps。

【问题讨论】:

    标签: javascript node.js ecmascript-6 es6-proxy


    【解决方案1】:

    部分

    let obj = Object.create(cstr.prototype)
    cstr.apply(obj, args)
    

    不适用于 ES6 类。你需要使用

    let obj = Reflect.construct(target, args, cstr);
    

    (而不是您尝试做的Reflect.construct(cstr, args)new cstr(...args),它确实无限递归-IIRC target 指的是_Recordcstr 指的是Record 或其子类之一)。

    【讨论】:

      猜你喜欢
      • 2017-04-19
      • 1970-01-01
      • 1970-01-01
      • 2013-04-30
      • 2022-08-06
      • 2020-05-10
      • 1970-01-01
      • 2021-12-03
      • 2017-08-28
      相关资源
      最近更新 更多