除了维护用于闭包的上下文之外,我不知道使用该模式有任何编程差异。也许这只是 ExtJS 使用的一种约定。
此外,正如 Daniel 所说,在缩小过程中可能会进一步缩短代码。 ExtJS、jQuery 等库非常关心文件大小,使用这种技术可能会节省足够的文件大小
例如1000 'this',假设 1 char = 1 byte,是 4kb。使用上述技术可能会减少 2 或 3 kb。
更新:继续做了一个小实验..
var test = {
a : function() {
this.x='';
this.x='';
this.x='';
this.x='';
this.x='';
this.x='';
this.x='';
this.x='';
this.x='';
this.x='';
this.x='';
this.x='';
},
b : function() {
this.x='';
this.x='';
this.x='';
this.x='';
this.x='';
this.x='';
this.x='';
this.x='';
this.x='';
this.x='';
this.x='';
this.x='';
},
c : function() {
this.x='';
this.x='';
this.x='';
this.x='';
this.x='';
this.x='';
this.x='';
this.x='';
this.x='';
this.x='';
this.x='';
this.x='';
}
}
缩小成
var test={a:function(){this.x="";this.x="";this.x="";this.x="";this.x="";this.x="";this.x="";this.x="";this.x="";this.x="";this.x="";this.x=""},b:function(){this.x="";this.x="";this.x="";this.x="";this.x="";this.x="";this.x="";this.x="";this.x="";this.x="";this.x="";this.x=""},c:function(){this.x="";this.x="";this.x="";this.x="";this.x="";this.x="";this.x="";this.x="";this.x="";this.x="";this.x="";this.x=""}}
同时
var test = {
a : function() {
var me=this;
me.x='';
me.x='';
me.x='';
me.x='';
me.x='';
me.x='';
me.x='';
me.x='';
me.x='';
me.x='';
me.x='';
me.x='';
},
b : function() {
var me=this;
me.x='';
me.x='';
me.x='';
me.x='';
me.x='';
me.x='';
me.x='';
me.x='';
me.x='';
me.x='';
me.x='';
me.x='';
},
c : function() {
var me=this;
me.x='';
me.x='';
me.x='';
me.x='';
me.x='';
me.x='';
me.x='';
me.x='';
me.x='';
me.x='';
me.x='';
me.x='';
}
}
缩小成
var test={a:function(){var a=this;a.x="";a.x="";a.x="";a.x="";a.x="";a.x="";a.x="";a.x="";a.x="";a.x="";a.x="";a.x=""},b:function(){var a=this;a.x="";a.x="";a.x="";a.x="";a.x="";a.x="";a.x="";a.x="";a.x="";a.x="";a.x="";a.x=""},c:function(){var a=this;a.x="";a.x="";a.x="";a.x="";a.x="";a.x="";a.x="";a.x="";a.x="";a.x="";a.x="";a.x=""}}
这意味着大约 10% 或多或少的字符(当然这取决于在代码的块范围内重复使用了多少“this”)。