给出一个简单的类
class Foo {
constructor(x) {
if (!(this instanceof Foo)) return new Foo(x);
this.x = x;
}
hello() {
return `hello ${this.x}`;
}
}
Run Code Online (Sandbox Code Playgroud)
是否可以在没有new关键字的情况下调用类构造函数?
用法应该允许
(new Foo("world")).hello(); // "hello world"
Run Code Online (Sandbox Code Playgroud)
要么
Foo("world").hello(); // "hello world"
Run Code Online (Sandbox Code Playgroud)
但后者失败了
Cannot call a class as a function
Run Code Online (Sandbox Code Playgroud) ECMAScript 2015规范提到关键字(或单词?)new.target正好3次 - 在14.2.3中 1次:
通常,Contains不会查看大多数函数表单但是,Contains用于检测ArrowFunction中的new.target,this和super用法.
在14.2.16中两次:
ArrowFunction不为arguments,super,this或new.target定义本地绑定.对ArrowFunction中的参数,super,this或new.target的任何引用 都必须解析为词汇封闭环境中的绑定
MDN提到它,但非常模糊,页面不完整.
巴别塔似乎不支持它.尝试在函数(箭头或其他)中使用new.target时出现语法错误.
它是什么,它应该如何使用?
我想创建一个构造函数对象,其继承正常工作,但捕获构造函数以便我可以操作实例对象。使用Proxy() 几乎解决了这个问题,但它似乎搞砸了继承。请注意以下没有代理的示例:
> const B = function() {}
undefined
> B.name
'B'
> class C extends B {}
[Function: C]
> B.prototype == C.prototype.__proto__
true
> var instance = new C()
undefined
> C.prototype == instance.__proto__
true
> instance.__proto__
C {}
Run Code Online (Sandbox Code Playgroud)
现在,如果我向 capture 添加一个代理construct(target,args),它将正确捕获构造函数,但它不会像没有代理那样完全保留内容。请注意,构造函数所做的只是向控制台打印一条消息,记录其捕获。但否则(我认为)它应该做出相同的反应。但是,当我创建一个类来扩展代理函数时,似乎扩展函数完全丢失了。请注意,最后四行给出的结果与上面不同。
> const handler = { construct(target,args) {
... console.log('Captured!'); return new target(...args); } }
undefined
> const proxy_B = new Proxy(B, handler)
undefined
> proxy_B.name
'B'
> class C2 extends proxy_B {} …Run Code Online (Sandbox Code Playgroud)