SoFunction
Updated on 2025-04-10

JavaScript class and inheritance instructions for using this property

This property represents the current object. If this is used within the global scope, it refers to the current page object window; if this is used in the function, this refers to what is called on the object on which this function is based on the runtime. We can also use two global methods apply and call to change the specific point of this in the function.
Let’s first look at an example of using this within the global scope of action:
Copy the codeThe code is as follows:

<script type="text/javascript">
(this === window); // true
( === ); // true
(("021", 10)); // 10
</script>

This property in a function is determined at runtime, not when the function is defined, as follows:
Copy the codeThe code is as follows:

// Define a global function
function foo() {
();
}
// Define a global variable, equivalent to = "apple";
var fruit = "apple";
// At this time, this in the function foo points to the window object
// This method of calling is completely equivalent to ();
foo(); // "apple"
// Customize an object and point the property foo of this object to the global function foo
var pack = {
fruit: "orange",
foo: foo
};
// This in function foo points to the object
(); // "orange"

The global functions apply and call can be used to change the pointing of this property in the function, as follows:
Copy the codeThe code is as follows:

// Define a global function
function foo() {
();
}
// Define a global variable
var fruit = "apple";
// Customize an object
var pack = {
fruit: "orange"
};
// Equivalent to ();
(window); // "apple"
// This === pack in foo
(pack); // "orange"

Note: The functions of apply and call are the same, the only difference is that the parameter definitions of the two functions are different.
Because functions are also objects in JavaScript, we can see the following interesting examples:
Copy the codeThe code is as follows:

// Define a global function
function foo() {
if (this === window) {
("this is window.");
}
}
// Function foo is also an object, so you can define the attribute boo of foo as a function
= function() {
if (this === foo) {
("this is foo.");
} else if (this === window) {
("this is window.");
}
};
// Equivalent to ();
foo(); // this is window.
// You can see this in the function pointing to the object calling the function
(); // this is foo.
// Use apply to change the pointing of this in the function
(window); // this is window.