The 'this' keyword behaves differently in Nodejs and browser

前端 未结 6 1864
栀梦
栀梦 2020-12-01 10:36

I have this piece of code :

var obj1;
var obj2;

function x() {
    obj1 = this;
}

function y() {
    obj2 = this;
}

x();
y();

console.log(obj1 === o         


        
6条回答
  •  既然无缘
    2020-12-01 11:23

    The difference is pretty simple

    In the node environment :

    this refers to module.exports or exports for short. but inside a function this is refering to the entire Node.js package.

    you can see it if you log to the console the following :

    function test(){
        console.log('this inside a function = ',this);
    }
    
    console.log('this outside a function = ',this);
    test();
    

    Whereas in the browser environment this inside a function or outside a function is referring to the window object unless you are using the new keyword which is another story.

    Execute the previous example in both Node.js and browser environments and you will understand.

提交回复
热议问题