This mechanism in JavaScript and javascriptthis Mechanism
JavaScript has its own set of this mechanism. In different cases, the point of this varies.
Global range
Console. log (this); // global variable
In the global range, this is used to point to the global variable. In the browser environment, this is the window.
Note: The strict mode of ECMAScript5 does not have a global variable. here this is undefined.
Function calling
Function foo () {console. log (this);} foo (); // global variable
This in function call also points to global variables.
Note: The strict mode of ECMAScript5 does not have a global variable. here this is undefined.
Object method call
Var test = {foo: function () {console. log (this) ;}} test. foo (); // test object
In an object method call, this points to the caller.
Var test = {foo: function () {console. log (this) ;}} var test2 = test. foo; test2 (); // global variable
However, due to the late binding feature of this, in the above case, this will point to a global variable, which is equivalent to directly calling a function.
This is very important. For the same code segment, this point can be determined only at runtime.
Constructor
Function Foo () {console. log (this);} new Foo (); // the newly created object console. log (foo );
Inside the constructor, this points to the newly created object.
Explicitly set this
Function foo (a, B) {console. log (this) ;}var bar ={}; foo. apply (bar, [1, 2]); // barfoo. call (1, 2); // Number object
Using the call or apply method of Function. prototype, this is set to the first parameter passed in.
Articles you may be interested in:
- Onclick (this) usage in javascript
- Details about the this keyword in js
- Introduction to the use of this variable in JS
- This is a detailed description of javascript Running Mechanism
- Summary of self and this usage in javascript
- Js this function call does not need to capture the id, name or tag name again
- Functions of Javascript learning notes (ii): Working Mechanism of this
- In-depth understanding of the scope of this in Javascript
- Example Analysis of JS function this usage
- Understanding of this keyword in js