Operator to set prototype of anonymous object directly

In a function, if you want to return an object with specific prototype, or no prototype, you may use Object.create, like:
function fun(){
var obj = Object.create(proto);
return obj;

but I just want to return an anonymous object ,i.e. return {a: 1, b:2 }
but current I cannot set the prototype directly.
maybe we need a new operator, for example, "->" to set the prototype.
so we can do something like this: return {a: 1, b: 2} -> proto

1 Like

You can do this with { __proto__: proto, a: 1, b: 2 }.

The __proto__ definition does only work in object literals, though (and is ugly imo because it looks like a property). An operator could work on arbitrary literals, like the once proposed <| proto operator.

That is only guaranteed to work in browser engines - other engines like Rhino and XS are under no obligation to implement that.

That depends on what you mean by "obligation". In practice, an engine which omits this will be unable run a lot of extant JS code. For that reason we have discussed pulling a bunch of stuff out of Annex B, including this particular syntax. (And in fact both Rhino and XS do implement it, as do other non-browser engines such as QuickJS and Hermes.)

1 Like