除了在闭包中保留上下文之外,我不知道使用该模式是否有任何程序上的区别。也许这只是ExtJS正在使用的一种约定。
此外,正如Daniel所指出的那样,这可能是为了在缩小代码时进一步缩短代码。像ExtJS、jQuery等库非常关心文件大小,使用这种技术可能会产生足够的文件大小节省。
例如,1000个'this',假设1个字符=1个字节,就是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”)。
this
这个想法? - Fake Name