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

前端 未结 4 1672
深忆病人
深忆病人 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

    Summary:

    In Javascript the value of this is determined when a function is called. Not when a function is created. In nodeJS in the outermost scope of a module the value of this is the current module.exports object. When a function is called as a property of an object the value of this changes to the object it was called. You can remember this simply by the left-of-the-dot rule:

    When a function is called you can determine the value of this by looking at the place of the function invocation. The object left of the dot is the value of this. If there is no object left of the dot the value of this is the module.exports object (window in browsers).

    caveats:

    • This rule does not apply for es2015 arrow function which don't have their own binding of this.
    • The functions call, apply, and bind can bend the rules regarding the this value.

    Example (NodeJS):

    console.log(this);  // {} , this === module.exports which is an empty object for now
    
    module.exports.foo = 5;
    
    console.log(this);  // { foo:5 }
    
    let obj = {
        func1: function () { console.log(this); },
        func2: () => { console.log(this); }
    }
    
    obj.func1();  // obj is left of the dot, so this is obj
    obj.func2();  // arrow function don't have their own this
                  // binding, so this is module.exports, which is{ foo:5 } 
    

    Output:

提交回复
热议问题