YUI Compressor壓縮失效的場景-eval和with

1、官方文檔的說明

in the face of evil features such as eval or with, the YUI Compressor takes a defensive approach by not obfuscating any of the scopes containing the evil statementjavascript

傳送門:官方文檔
翻譯成中文就是說:eval和with語句所處的做用域,YUI Compressor是不進行壓縮混淆單詞的。html

2、普通代碼測試

1)源代碼java

function testCompressor(){
    // 測試YUI Compressor
    var person = {
            'name':'wall',
            'jser':true
        };
        
    console.log("my name is "+ person.name);
}

2)壓縮後從新格式化的代碼git

function testCompressor() {
    var a = {
        name: "wall",
        jser: true
    };
    console.log("my name is " + a.name)
};

3、含有eval代碼測試

1)源代碼github

function testCompressor(){
    // 測試YUI Compressor
    var person = {
            'name':'wall',
            'jser':true
        };
        
    console.log("my name is "+ person.name);
    eval("console.log(\"I am Jser\");");
}

2)壓縮後從新格式化的代碼app

function testCompressor() {
    var person = {
        name: "wall",
        jser: true
    };
    console.log("my name is " + person.name);
    eval('console.log("I am Jser");')
}

結論:只要eval存在的做用域,代碼都沒法作混淆操做。測試

4、解決方案

 既然沒法改變這個規則,那就要儘可能去避免代碼中直接出現eval。能夠講eval封裝起來調用。
1)源代碼ui

function testCompressor(){
    // 測試YUI Compressor
    var person = {
            'name':'wall',
            'jser':true
        };
        
    console.log("my name is "+ person.name);
    myEval("console.log(\"I am Jser\");");
}

function myEval(data){
    return eval(data);
}

2)壓縮後從新格式化的代碼翻譯

function testCompressor() {
    var a = {
        name: "wall",
        jser: true
    };
    console.log("my name is " + a.name);
    myEval('console.log("I am Jser");')
}
function myEval(data) {
    return eval(data)
}

3)另外一種解決方式: 改成window["eval"]進行調用code

function testCompressor(){
    // 測試YUI Compressor
    var person = {
            'name':'wall',
            'jser':true
        };
        
    console.log("my name is "+ person.name);
    window["eval"]("console.log(\"I am Jser\");");
}

with 也適用上述的解決方案

原文入口:http://www.jianshu.com/p/67973651e398

相關文章
相關標籤/搜索