9

インターネットで、次の構造を使用してグローバルオブジェクトを取得する人々を見ました

(1,eval)('this')

またはこれ

(0||eval)('this')

windowそれがどのように機能し、 、 、などよりも優れているかを説明していただけますtopか?

UPD : 直接呼び出しと間接eval呼び出しのテスト: http://kangax.github.io/jstests/indirect-eval-testsuite/

4

1 に答える 1

2

(1,eval)('this')と同等ですeval('this')

(0||eval)('this')と同等ですeval('this')

したがって、 (1, eval) または (0 || eval) はevalを生成する式です

のように:

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

ここで唯一の問題は、式から返されるオブジェクトは常に最もグローバルなスコープを持つオブジェクトであるということです。

そのコードを確認してください:

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();
于 2013-09-19T07:51:52.113 に答える