Meaning of “this” in node.js modules and functions

前端 未结 4 1900
深忆病人
深忆病人 2020-11-22 04:34

I have a JavaScript file which is loaded by require.

// loaded by require()

var a = this; // \"this\" is an empty object
this.anObject = {name:         


        
4条回答
  •  我寻月下人不归
    2020-11-22 04:58

    To understand this, you need to understand that Node.js actually wraps your module code in to a function, like this

    (function (exports, require, module, __filename, __dirname) {
        var test = function(){
            console.log('From test: '  + this);
        };
        console.log(this);
        test();
    });
    

    Detailed explanation can be found in this answer.


    Now, this wrapped function is actually invoked like this

    var args = [self.exports, require, self, filename, dirname];
    return compiledWrapper.apply(self.exports, args);
    

    So, this, at the module level, is actually the exports object.

    You can confirm that like this

    console.log(this, this === module.exports);
    // {} true
    

提交回复
热议问题