This attribute indicates the current object. If this is used in the global scope, it indicates the current page Object window. If this is used in the function, this indicates what is called Based on the object on which the function is called at runtime. We can also use the apply and call global methods to change the specific point of this in the function.
First, let's look at an example of using this in the global scope:
- < script type="text/javascript">
- console.log(this === window); // true
- console.log(window.alert === this.alert); // true
- console.log(this.parseInt("021", 10)); // 10
- < /script>
The this attribute in a function is determined at runtime rather than at function definition, as follows:
- // Define a global function
- Function foo (){
- Console. log (This. Fruit );
- }
- // Define a global variable, which is equivalent to window. fruit = "apple ";
- Var fruit ="Apple";
- // In this case, the function foo points to the window object.
- // This call method is equivalent to window. foo ();
- Foo ();// "Apple"
-
- // Customize an object and direct its property foo to the global function foo
- Var pack = {
- Fruit:"Orange",
- Foo: foo
- };
- // In this case, the function foo points to the window. pack object.
- Pack. foo ();// "Orange"
-
The global functions apply and call can be used to change the point of this attribute in the function, as follows:
- // Define a global function
- Function foo (){
- Console. log (This. Fruit );
- }
- // Define a global variable
- Var fruit ="Apple";
- // Customize an object
- Var pack = {
- Fruit:"Orange"
- };
- // Equivalent to window. foo ();
- Foo. apply (window );// "Apple"
- // This = pack in foo
- Foo. apply (pack );// "Orange"
Note: The apply and call functions have the same functions. The only difference is that the parameter definitions of the two functions are different.
Because functions in JavaScript are also objects, we can see the following interesting example:
- // Define a global function
- Function foo (){
- If(This=== Window ){
- Console. log ("This is window .");
- }
- }
-
- // The function foo is also an object, so the boo attribute of foo can be defined as a function.
- Foo. boo = function (){
- If(This=== Foo ){
- Console. log ("This is foo .");
- }Else If(This=== Window ){
- Console. log ("This is window .");
- }
- };
- // Equivalent to window. foo ();
- Foo ();// This is window.
-
- // You can see this in the function pointing to the object that calls the function.
- Foo. boo ();// This is foo.
-
- // Use apply to change the point of this in the function
- Foo. boo. apply (window );// This is window.
- Summary of three + 1 implementation methods of ExtJS Grid Tooltip
- Implementation of JavaScript asynchronous call framework chain
- JQuery-style chained call of JavaScript asynchronous call framework
- Code Implementation of the JavaScript asynchronous call framework
- JavaScript asynchronous call framework case design