普通に関数の場合は new コンテキストじゃなければ中で new したのを返せばいいけどそれもできない
function Foo(a) {
if (this === window || !this) return new Foo()
this.value = a
}
構文を使わなくしたり ラップしたり
const unew = (ctor, proto) => (...a) => {
const ctx = { __proto__: proto }
return ctor(ctx, ...a) || ctx
}
const F = unew(
(self, a, b) => {
self.value = a
self.value1 = self.m(b)
},
{
m(x) {
return this.value + x
},
p() {
return this.value1
},
}
)
F("a", "b").p()
// ab
const unew2 = cls => (...a) => new cls(...a)
const G = unew2(
class {
constructor(a, b) {
this.value = a
this.value1 = this.m(b)
}
m(x) {
return this.value + x
}
p() {
return this.value1
}
}
)
G("a", "b").p()
// ab