缩小javascript使函数不可调用

时间:2015-11-04 22:39:27

标签: javascript gulp uglifyjs

我使用gulp为我的项目构建资产管道。我目前正在使用gulp-uglify来缩小javascript。

当Uglify处理我的JS时,它会更改函数名称,这使得它不可调用。有谁知道如何防止这种情况发生?

(function() { "use strict";

  function Ajax(params, url, callbackFunction) {
    this.params = params,
    this.url = url,
    this.callback = callbackFunction
  }

  Ajax.prototype.call = function() {
    $.ajax({
      contentType: "application/json; charset=utf-8",
      dataType: "json",
      type: "post",
      data: this.params,
      success: this.callback,
      error: this.callback
    });
  }
})();

变为

!function(){"use strict";function t(t,a,s){this.params=t,this.url=a,this.callback=s}t.prototype.call=function(){$.ajax({contentType:"application/json; charset=utf-8",dataType:"json",type:"post",data:this.params,success:this.callback,error:this.callback})}}();

这改变了要调用的Ajax函数" t"当我想实例化一个新的Ajax对象时,我得到一个Uncaught ReferenceError: Ajax is not defined

我的主叫代码是

$(document).ready(function() {
  var ajaxTest = new Ajax("google.com", {}, printTest);
  console.log(ajaxTest);
  Ajax.call();

  function printTest() {
    console.log("Hello");
  }
});

缩小为

$(document).ready(function(){function o(){console.log("Hello")}var l=new Ajax("google.com",{},o);console.log(l),Ajax.call()});

1 个答案:

答案 0 :(得分:1)

缩小过程没有任何问题。 Ajax标识符是作用域的本地标识符,因此无论如何都无法在作用域之外访问它。该范围内将使用Ajax标识符的任何代码都将缩小为使用t标识符。

如果要在作用域外使用Ajax标识符,可以从函数包装器返回它:

var Ajax = (function() { "use strict";

  function Ajax(params, url, callbackFunction) {
    this.params = params,
    this.url = url,
    this.callback = callbackFunction
  }

  Ajax.prototype.call = function() {
    $.ajax({
      contentType: "application/json; charset=utf-8",
      dataType: "json",
      type: "post",
      data: this.params,
      success: this.callback,
      error: this.callback
    });
  };

  return Ajax;
})();

现在,您可以在其他代码中使用Ajax标识符。如果通过缩小代码来更改范围之外的Ajax标识符,则使用该代码的代码也将使用该新标识符。