Home > Web Front-end > JS Tutorial > body text

Detailed explanation of this in Nodejs_node.js

WBOY
Release: 2016-05-16 15:07:56
Original
1587 people have browsed it

The following content is all about this in nodejs rather than this in javascript. This in nodejs is different from this in javascript in the browser.

this

in global
console.log(this); {}
this.num = 10;
console.log(this.num); 10
console.log(global.num); undefined
Copy after login

This in the global world is an empty object by default. And in the global this has no relationship with the global object, so who exactly does this in the global point to? We will explain this in the second half of this chapter.

this

in a function
function fn(){
  this.num = 10;
}
fn();
console.log(this); {}
console.log(this.num); undefined
console.log(global.num); 10

Copy after login

This in the function points to the global object, which is not the same object as this in the global. Simply put, the variable you define through this in the function is equivalent to adding an attribute to global. At this time, it is the same as global. The "this" in "has nothing to do with it".

If you don’t believe it, look at the code below to prove it.

function fn(){
  function fn2(){
    this.age = 18;
  }
  fn2();
  console.log(this); global
  console.log(this.age); 18
  console.log(global.age); 18
}
fn();

Copy after login

Right, in the function this points to global.

this

in the constructor
function Fn(){
  this.num = 998;
}
var fn = new Fn();
console.log(fn.num); 998
console.log(global.num); undefined
Copy after login

In the constructor, this points to its instance, not global.

We can now talk about this in the global context. Speaking of this in the global context, it actually has something to do with the scope in Nodejs. If you want to know more about the scope in Nodejs, you can read the discussion about scope in Nodejs. Scope issue. this article.

Back to the topic, this in the global context points to module.exports.

this.num = 10;
console.log(module.exports); {num:10}
console.log(module.exports.num);
Copy after login

Why does this point to module.exports in the global view? Then you need to know more about module.exports first. For the time being, we will know this first. We will talk about module if we have the opportunity later

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template