Node.js "this" in closure



  • I'm trying to make a JavaScript code generator's output work with the Closure compiler, but I'm having a problem getting the code to work properly in the first place.

    I'll show instead of telling:

    $ cat test.js 
    (function() { console.log(this.Array); }).call(this);
    $ node test.js 
    undefined
    $ node < test.js 
    [Function: Array]
    $ node -v
    v0.10.25
    

    @GLaDOS

    !compiler compile

    (function() { console.log(this.Array); }).call(this);
    


  • @GLaDOS

    !compiler compile

    (function() { console.log(this.Array); }).call(this);
    

    (i need to work on this module a little more)


  • SockDev

    huh......

    accalia@Misha:~$ echo '(function() { console.log(this.Array); }).call(this);'>  test.js                      
    accalia@Misha:~$ node -e '(function() { console.log(this.Array); }).call(this);'
    [Function: Array]
    accalia@Misha:~$ node test.js
    undefined
    accalia@Misha:~$ node <test.js
    [Function: Array]
    accalia@Misha:~$ node --version
    v0.12.5
    accalia@Misha:~$
    

    what the.......?

    accalia@Misha:~$ echo 'console.log(this);'>  test.js                                           
    accalia@Misha:~$ node test.js
    {}
    accalia@Misha:~$ node <test.js                                                         
    { global: [Circular],
    [SNIP]
    cache: {} } }
    accalia@Misha:~$
    

    huh..... different values of this.... i wonder why....?


  • SockDev

    you might be able to get away with replacing that closure call with

    (function() { console.log(this.Array); }).call(this||global);
    

    ???



  • The problem is that the Closure Compiler complains about an undeclared variable named global. And your code won't work because {} is truthy.


  • SockDev

    well here's a question why are you closing over this in the first place?

    i mean it's well documented that what you get for this is a crapshoot anyway, and if you're developing for node as you appear to be it's an antipatern to enclose your module in a closure anyway because node gives you that isolation as part of the module structure.

    if i knew the why of this, possibly with a less contrived example than trying to find the Array class (which you shouldn't be trying to get via this anyway) i could be of more help.

    if you must close over this....

    /*global global */
    var module = this;
    if (Object.keys(this).length < 1) { // empty this object
        module = global;
    }
    (function() { console.log(this.Array); }).call(module);
    

    that should set you straight. assuming that closure compiler respects the jslint style global tag.


Log in to reply
 

Looks like your connection to What the Daily WTF? was lost, please wait while we try to reconnect.