Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comma operator to reset this

Tags:

typescript

In following code

var x = { f: function () { return this === window } };
(0, x.f)();

I'm using construction (0, x.f) to run function with this equal to Window (or undefined in strict mode).

But typescript says

Left side of comma operator is unused and has no side effects.

But actually there is a side effect on this of function I'm calling.

How should I write my code to eliminate this error message?

like image 673
Qwertiy Avatar asked Jan 14 '18 20:01

Qwertiy


People also ask

What does comma operator do?

The comma operator ( , ) evaluates each of its operands (from left to right) and returns the value of the last operand. This lets you create a compound expression in which multiple expressions are evaluated, with the compound expression's final value being the value of the rightmost of its member expressions.

What is the comma operator in C?

The comma operator in c comes with the lowest precedence in the C language. The comma operator is basically a binary operator that initially operates the first available operand, discards the obtained result from it, evaluates the operands present after this, and then returns the result/value accordingly.

What does comma mean in JS?

A comma operator (,) in JavaScript is used in the same way as it is used in many programming languages like C, C++ etc. This operator mainly evaluates its operands from left to right sequentially and returns the value of the rightmost operand.

How do commas work in Python?

On the left-hand side of an assignment, the comma indicates that sequence unpacking should be performed according to the rules you quoted: a will be assigned the first element of the tuple, b the second.


1 Answers

Zero itself really doesn't have side effects, but comma operator does.

So the possible solution is to add as any to 0:

var x = { f: function () { return this === window } };
(0 as any, x.f)();
like image 184
Qwertiy Avatar answered Sep 19 '22 13:09

Qwertiy