我正在尝试代理 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)
如果运行此代码片段,您将收到以下错误:
cstr.apply(obj, args)
TypeError: Class constructor _Record cannot be invoked without 'new'
如果我用 new cstr
替换 cstr.apply
,构造函数会很快耗尽堆栈(显然会进入无限递归)。
如果我用函数替换 _Record
类,这个可以工作(例如,通过 Babel 转译这个可以工作)。我可以让它与原生 ES6 一起工作吗?
谢谢。
P。 S. 我目前正在 Node 7.7.4 上检查这些片段(如果重要的话)。
最佳答案
部分
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
引用 _Record
,而 cstr
引用 Record
或其子类之一。
关于javascript - 尝试代理 ES6 类构造函数时出现 TypeError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43104420/