Different from inside the browser:

Create the main js

   function test() {
      this.names = "anikin";
    }
    this.names = 'zhangsan';
    test();
    
    console.log(this.this.name)  // {} zhangsan
    console.log(global.names) // aninkin
    
     // Let's print this and see where it points
     console.log(this= = =module.exports); // true
Copy the code

The above code analysis leads to several conclusions:

  • Inside the functionthisThe point is globalglobal.
  • The entire run filethisIs pointing tomodule.exports. You can refer to thatModularity principle.

Exports = module.exports. So we can use this to verify that.

Js is a very basic reference.

var a = { name: "anikin" };
var b = a;
a = { age: 23 };

console.log(a, b); 
Copy the code

The output is: {age: 23} {name: “anikin”}.

So verify the relationship of exports above. Create file test.js:


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

//
exports.c = 3;
module.exports = {
  a: 1.b: 2};this.m = 5;

console.log(this);  
console.log(this= = =exports);
console.log(this= = =module.exports);
console.log(module.exports);

Copy the code

The output is:

 { c: 3.m: 5 }
true
false
{ a: 1.b: 2 }

Copy the code

When a file is read, the file access function __temp.call is called internally

  • Exports = exports; exports = exports; exports = exports; The require function returns module.exports, which in turn returns an empty {} object.

  • / / exports = 0; / / exports = 0; }}} {c:3}}}}}}}}}}}}}}}}}}}}}}}}}

  • module.exports={a:1,b:2}; Now when you change the value, you create a new address reference in the heap and point to the new room,

Exports are not equal to this. Exports are not equal to this

Same point as the browser:

This is a browser-side implementation for objects, classes, arrow functions, etc.

For example, the arrow function: this is bound when the function is defined, not during execution. Simply put, when a function is defined, this inherits from the object that defines the function.

const Events = require("events");
class MyEvent extends Events {}
var e1 = new MyEvent();

e1.on("start".function () {
  console.log("start:event ".this.this === e1);
});

e1.on("start".() = > {
  console.log("start:event ".this.this === e1);
});

e1.emit("start"."anikin");
Copy the code

The result of execution is:

 anikin MyEvent true
 {} false
Copy the code