On the problem of this direction in function

  node.js, question

This point in function is always confusing.

document.body.onclick = function(){
 console.log(this);  //this this points to body.
 function click_inner(){
 console.log(this);  //this this points to window

It can be inferred from the above code that each function has a this.

My original understanding was: there is no this in click_inner, but there is this in its upper function, so according to JS’s scope and scope chain’s knowledge (variables that are not inside go back to the upper environment to find and return when found), this inside is this in the variable object of the external function.

According to my original understanding: then this operating in click_inner should also point to body, but the result clearly shows that I was wrong in my original understanding. . .

According to the results, this in click_inner also points to window, but whywindow.click_inner()Just report the mistake? As if to overturn the above speculation. .

Please explain your knowledge about this in detail. . Thank you very much! !

This of javascript is mainly about how to call this function, not the scope of this function.obj.fn()This in fn is obj.fn()This is undifine, and before js enters the function, there will beif(! this) { this = window}This kind of operation. Therefore, the latter this iswindow.

To sum up,thisThere are six different values:

  1. Normal function call, this is a global object or undefined

  2. As the method of the object, this is the object

  3. New expression, this is a newly created object based on this function

  4. Use apply/call to specify this

  5. Bind a fixed this with bind

  6. This in the event handler is the DOM element that currently triggers the event (event.currentTarget)

For details, see:http://zonxin.github.io/post/2015/11/javascript-this