The This property represents the current object, or refers to the current Page Object window if this is used globally, and if this is used in a function, this refers to what is invoked on the object based on this function at run time. We can also use apply and call two global methods to change the specific point of this in the function.
Let's look at an example of using this in a global scope:
Copy Code code as follows:
<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 property in a function is determined at run time, not when the function is defined, as follows:
Copy Code code as follows:
Define a global function
function foo () {
Console.log (This.fruit);
}
Defines a global variable, equivalent to Window.fruit = "Apple";
var fruit = "Apple";
This points to the Window object in function foo
This invocation mode and Window.foo () are completely equivalent
Foo (); "Apple"
Customize an object and point the object's property foo to the global function foo
var pack = {
Fruit: "Orange",
Foo:foo
};
This points to the Window.pack object in function foo
Pack.foo (); "Orange"
Global functions apply and call can be used to change the point of this property in a function, as follows:
Copy Code code as follows:
Define a global function
function foo () {
Console.log (This.fruit);
}
Define a global variable
var fruit = "Apple";
Customizing an Object
var pack = {
Fruit: "Orange"
};
Equivalent to Window.foo ();
foo.apply (window); "Apple"
The This = = Pack in foo
Foo.apply (Pack); "Orange"
Note: Apply and call two functions have the same function, the only difference is that the parameters of the two functions are defined differently.
Because functions are also objects in JavaScript, we can see the following interesting examples:
Copy Code code as follows:
//define a global function
function foo () {
if (this = = window) {
Console. Log ("This is window.");
}
}
//function foo is also an object, so you can define Foo's property boo to 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 the object in the function that points to the calling function
Foo.boo ();//is foo.
//Using apply to change this in function to point to
foo.boo.apply (window);