我正在寻找一种方法来缩小这样的代码:
setTimeout(function() {
  document.getElementById('test').innerText = 'Hello World!';
}, 1000);(减去空格和新行):
(function(a,b){
  a(function(){
    b('test').innerText='Hello World!';
  }, 1000);
})(setTimeout, document.getElementById)使用自动工具,如UglifyJS或类似工具。从文档来看,这样做似乎不是一种选择。
编辑:看到这样的代码是很常见的:
(function (window, document, undefined) {
  // code here
})(window, document);这是针对性能和使代码更易于小型化。的,所以我想知道为什么没有在更深的层次上这样做。
发布于 2021-12-31 13:22:16
使用丑js (用3.14.5版本测试它,但也应该使用版本2),您可以使用--enclose选项:
npx uglify-js --mangle --enclose setTimeout,document:setTimeout,document test.js --output test2.js给出以下输出:
(function(e,t){e(function(){t.getElementById("test").innerText="Hello World!"},1e3)})(setTimeout,document);不幸的是,它不能替代像document.getElementById这样的表达式。
https://stackoverflow.com/questions/42024170
复制相似问题