Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does indirect eval work [duplicate]

Tags:

javascript

I saw on the Internet that people using following construction to get Global object

(1,eval)('this')

or this

(0||eval)('this')

Could you explain how exactly does it work and the benefit over window, top, etc.?

UPD: testing direct vs. indirect eval calls: http://kangax.github.io/jstests/indirect-eval-testsuite/

like image 747
hazzik Avatar asked Sep 19 '13 04:09

hazzik


People also ask

How does the indirect formula work?

The Excel INDIRECT Function[1] returns a reference to a range. The INDIRECT function does not evaluate logical tests or conditions. Also, it will not perform calculations. Basically, this function helps lock the specified cell in a formula.

How do you reference an indirect worksheet to another sheet in Excel?

Using Excel INDIRECT function to lock a cell reference Enter any value in any cell, say, number 20 in cell A1. Refer to A1 from two other cells in different ways: =A1 and =INDIRECT("A1") Insert a new row above row 1.


1 Answers

(1,eval)('this') is equivalent to eval('this')

(0||eval)('this') is equivalent to eval('this')

So (1, eval) or (0 || eval) is an expression which yields eval

Like in:

var x = 2;
console.log( (10000, x) );  // will print 2 because it yields the second variable
console.log( (x, 10000) );  // will print 10000 because it yields the second literal
console.log( (10000 || x) ); // will print 10000 because it comes first in an OR
                             // expression

The only catch here it that an object returned from an expression is always the object having the most global scope.

Check that code:

x = 1;

function Outer() {
    var x = 2;
    console.log((1, eval)('x')); //Will print 1
    console.log(eval('x')); //Will print 2
    function Inner() {
        var x = 3;
        console.log((1, eval)('x')); //Will print 1
        console.log(eval('x')); //Will print 3
    }
    Inner();
}

Outer();
like image 147
Rami Avatar answered Sep 25 '22 13:09

Rami