Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the reason for assigning this to a locale variable without a callback?

As far as I know assigning this to a variable is used within callbacks where the this scope may change. But digging through the ExtJS source I found it used in all sorts of functions but not always. So is there any reason that I would assign this to a local variable beneath the scope or is the ExtJS source just struggling with different developer styles?

like image 363
JJR Avatar asked Jul 22 '13 12:07

JJR


1 Answers

@kevhender pointed me to the right sencha forum thread where evan has given a very good explanation.

It's only for the size. And here's a example:

function doA() {
    var me = this;

    me.a();
    me.b();
    me.c();
    me.d();
    me.e();
    me.f();
    me.g();
    me.h();
    me.i();
    me.j();
    me.k();
    me.l();
}

function doB() {
    this.a();
    this.b();
    this.c();
    this.d();
    this.e();
    this.f();
    this.g();
    this.h();
    this.i();
    this.j();
    this.k();
    this.l();
}

Compressed we get:

function doA(){var a=this;a.a();a.b();a.c();a.d();a.e();a.f();a.g();a.h();a.i();a.j();a.k();a.l()}
function doB(){this.a();this.b();this.c();this.d();this.e();this.f();this.g();this.h();this.i();this.j();this.k();this.l()};

It adds up.


According to that we should

  • NOT use a local var if we use this only up to three times

    function doA(){var a=this;a.a();a.b();a.c();};
    function doB(){this.a();this.b();this.c();};
    
  • and use it if we use this more often then three times

    function doA(){var a=this;a.a();a.b();a.c();a.d()};
    function doB(){this.a();this.b();this.c();this.d()};
    
like image 162
JJR Avatar answered Sep 23 '22 15:09

JJR