tannerntannern / ts-mixer

A small TypeScript library that provides tolerable Mixin functionality.
MIT License
379 stars 27 forks source link

Caveat 3 is not true #49

Closed ckohen closed 2 years ago

ckohen commented 2 years ago

Caveat 3 states there is no way to call the constructor of a class with the correct this context. This is in fact not true.

As can be seen in the examples at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Reflect/construct a simple statement change can achieve just that.

// Replace
new constructor(...args);
// With
Reflect.construct(constructor, args, this);

Am I missing something here?

I believe I see where this change would need to be made, but I'm not 100% sure so I am making this issue first.

tannerntannern commented 2 years ago

@ckohen, thanks for digging into this. Unfortunately, I don't believe Reflect.construct can be used as you describe. The third parameter is supposed to be another constructor (from which another prototype can be referenced), not a this parameter. As I understand it, Reflect.construct's only advantage over new is being able to use a constructor and prototype from two different classes. It does not solve the issues outlined in caveat 3. As far as I know, no such function exists that does what you describe. (But it's a shame because it would be lovely if one did!)

You may have already seen this section of the README, but this documents the best workaround we have at the moment.

ckohen commented 2 years ago

Ah, I see, the "without new" threw me off for some reason since Reflect.construct isn't "new" persay. But yeah, that's an interesting use case that I think is probably way less useful, but so it is. I don't think this is an issue for me at all, just noticed it while reading up.