Google Closure Compiler: How to preserve code that caches “this”?

元气小坏坏 提交于 2019-12-05 21:57:19

You are attempting to out-think the compiler. It's a losing battle. However, here's the two main reasons people try to do this type of thing.

  1. Reduce size of code. The theory being that a single letter variable is smaller than the keyword this. However, this theory is flawed in most cases. See the compiler FAQ.

  2. Prevent the context of the keyword this from changing. However, in SIMPLE_OPTIMIZATIONS this is unnecessary. If you create an inner closure that references your variable, the compiler will not inline the value. Under ADVANCED_OPTIMIZATIONS, using the keyword this can be dangerous outside of a prototype function or constructor and should be done with care. See an article explaining why.

If you really want to prevent the compiler from inlining your value, you'll need to add it as a property on an object using quoted syntax:

(function() {
  var config = {};
  config['that'] = this;
})()

I suppose if you really have to you could do this:

(function() {
  var that = this || 1;
  that.a = 3;
  that.b = 4;
  this.c = 5;
  return that;
}());
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!