tc39 / proposal-shadowrealm

ECMAScript Proposal, specs, and reference implementation for Realms
https://tc39.es/proposal-shadowrealm/
1.43k stars 67 forks source link

Is wrapping `this` the right choice? #361

Closed mgaudet closed 2 years ago

mgaudet commented 2 years ago

While implementing ShadowRealms I've also been playing with it a bit.

I'm curious about the design decision around the WrappedFunction [[Call]] internal method. That method wraps the this value; which then requires that this be either a primitive or callable.

This can lead to some surprising behaviour; for example, you cannot do setTimeout on a wrapped function object, because it explicitly sets the this value to an object, which isn't callable

var h = realm.evaluate('() => log("Heyho")') 
setTimeout(h, 0); // Throws on execution.

In general, given that from the perspective of the target function, the this value will always either a primitive or a wrapped function... there's relatively little to the target function by the this value; which makes me wonder: should the [[Call]] internal method instead provide some sensible default this (i.e. undefined), or is there a way in which wrapping this is actually important?

I mean, I suppose you could imagine j = realm.evaluate('function f() { this("why"); }; f'); j.call(console.log), but I'm not sure about prioritizing that usage over the ability to pass a WrappedFunction object to APIs that may try to invoke it with a different (object) this.

mhofman commented 2 years ago

Duplicate of https://github.com/tc39/proposal-shadowrealm/issues/328