9

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/

hazzik
  • 13,019
  • 9
  • 47
  • 86

1 Answers1

2

(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();
Rami
  • 7,162
  • 1
  • 22
  • 19