【问题标题】:closure compiler / uglifyjs - this.function name not shortened?闭包编译器/uglifyjs - this.function 名称没有缩短?
【发布时间】:2011-08-06 18:40:16
【问题描述】:

如果我通过闭包编译器或 uglifyjs 运行这段代码,this.init 不会缩短。谁能告诉我这是为什么?

function test() {
    var v = "abc";
    this.init = function() {
         alert('var = ' + v + ' and func = ' + f());
         f2();
    }
    function f() {
        return 'def';
    }
    function f2() {
        v = "ghi";
        alert('blabla');
        alert('filler');
    }
}

test();

uglifyjs 把它变成:

function test(){function c(){a="ghi",alert("blabla"),alert("filler")}function b(){return"def"}var a="abc";this.init=function(){alert("var = "+a+" and func = "+b()),c()}}test()

美化即:

function test() {
    function c() {
        a = "ghi", alert("blabla"), alert("filler")
    }
    function b() {
        return "def"
    }
    var a = "abc";
    this.init = function () {
        alert("var = " + a + " and func = " + b()), c()
    }
}

test()

那么为什么 this.init() 没有更改为更短的名称呢?

另外,做的到底有什么区别:

 function init() {..}

和

 this.init = function() { .. }

谢谢, 卫斯理

【问题讨论】:

    标签: jquery function compression google-closure-compiler uglifyjs


    【解决方案1】:

    init 未缩短的原因与 test 未缩短的原因相同...因为它是您代码的公共 API 的一部分。

    当您调用var t = new test() 时,您将创建一个如下所示的对象:

    {
        init: function() { ... },
        prototype: test
    }
    

    您可以致电t.init()。如果编译器不尊重那些在全局范围内可用的变量,那么您必须在缩小 JavaScript 代码之前将 all 内联到一个文件中。否则,每次您缩小 test.js 时,公共函数 test 的名称都会更改。所以这段代码:

    <script type="text/javascript" src="js/test.min.js"></script>
    <script type="text/javascript">
    var t = new test();
    t.init();
    </script>
    

    会中断(因为 test 会可能被缩小器更改为 a 并初始化为其他一些字母。)

    至于您问题的第二部分,当您执行 this.init = function 时,您正在为不确定的对象设置一个属性(它可以是任何东西,因为 this 是在 JavaScript 中的调用时设置的,并且您在里面声明它函数test)。当您编写 function init(){} 时,您正在编写 function declaration,它将被提升到封闭范围的顶部(这意味着您可以在定义它之前在定义它的范围内调用它。)但是,它在test 之外不可用。

    【讨论】:

    • 公共 api?我什至不叫它。任何以“this”开头的函数都会发生这种情况。 -- 假设这都是公共方法吗?
    • @Wesley - 在这个特定的例子中你是否调用它并不重要。重要的是 init 函数是 test 构造函数的可公开访问的成员,因此它的名称不能缩短/缩小,否则您的代码的使用者可能会尝试调用 new test().init() 并返回 undefined .
    • @Wesley,Uglify 也无法判断您是否在此脚本之后包含另一个使用“init”的脚本。
    • 如果你使用 Closure Compiler 的 ADVANCED 模式进行全局代码删除,它会缩短,但它对声明外部名称变量和属性有严格的规定。
    • 如果闭包编译器发现没有人调用它,除非您明确将其声明为extern,否则它将被缩短
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多