1, JS function call process, the JS thread will enter the new execution environment and create a variable object of the environment, the initialization of the variable object will automatically add two variables: this and arguments, so you can use these two variables in the function. It is important to note that the this variable cannot be re-assigned, and arguments can, as follows:
function Test () { var name = ' Test2 '; = window; This // in this line JS run will error }
2. This is the function object that is used to execute the function according to the value
2.1 When a function is executed at the global scope, this refers to the Global (window); When the function executes on an object, this refers to the object itself; When the function is called in another function, this also refers to the Global (window), as follows:
var name = ' window '; var obj = { name:' obj ', action:test } Test (); Obj.action (); Test2 (); function test2 () { var name = ' Test2 '; Test (); } function Test () { alert (this. Name) }
The above code responds in order: window, obj, window
The This in the 2.2 event response is divided into two cases:
A, HTML event definitions, such as:
<div style= "width:100px; border:solid; "id=" btn "onclick=" Test () ">doSomething</div>
In this case, this in test is the window
B, JS event definitions, such as
<div style= "width:100px; border:solid; "id=" btn "title=" Hello,boy ">doSomething</div> <script type=" Text/javascript "> document.getElementById (function () { alert (this. title); }; $ (' #btn '). Click (function () { alert (this. title); })
<script>
Whether native JS or jquery, this refers to the HTML element of the event object itself, and is a native JS object (not a jquery object)
Also, for HTML events, the This is the HTML element of the event object that is referenced directly in the event, as follows:
<div style= "width:100px; border:solid; "id=" btn "onclick=" test (This) ">doSomething</div>
The reason is that the quotation marks are actually JS statements, JS will implicitly generate an anonymous function, so essentially the same as the JS event
The different meanings of this in the JS function