A couple of years ago, I wanted figure how to create a type check for class A that returns true only for objects instantiated by new A(). For this, I wrote the class like this:
class A {
static #instances = new WeakSet();
static isInstance (value) {
return A.#instances.has(value);
}
constructor () {
if (new.target === A) {
A.#instances.add(this);
}
}
}
Any instance of a class that extends A thus would return false when passed to A.isInstance. But, then I realized that this can be faked by using Reflect.construct(B, [], A). What I did, then, was create a proxy whose construct trap would only pass A as newTarget if it met some condition. I've been trying to recall what that condition was, but while experimenting to rediscover it, I'm beginning to think that my old solution might not've worked.
Is there some way to achieve my desired effect here?
A.isInstance. So what's your concrete requirements, what's your actual use case? What goal do you try to achieve by checking "only for objects instantiated bynew A()"?A.isInstanceor not is outside the scope of the question. Pretend the class is frozen, pretend it's a global variable, pretends it's preserved in behind-the-scenes code like Node's library, and so on.new (class B extends A {})different thannew function B() { return new A() }? Why do you need to prevent it?Reflect.constructor(A, [])? Do you consider that to not be created bynew A()either? Again, why do you care? Anew B()is indistinguishable from anew A()whose prototype chain was messed with or that got extra properties added.isInstancecode in your question does work for that criterion already. "I realized that this can be faked by usingReflect.construct(B, [], A)" - only ifBcallsA(e.g. viasuper()). Same for subclasses ofSet.