The this attribute represents the current object. If this is used in the global scope, it refers to the current page object window; if this is used in a function, this refers to what object this function is called on at runtime. We can also use the two global methods apply and call to change the specific pointer of this in the function.
Let’s first look at an example of using this in the global scope:
The this attribute in the function is It is determined at runtime, not when the function is defined, as follows:
// Define a global function
function foo() {
console.log(this.fruit);
}
// Define a global variable, equivalent to window.fruit = "apple ";
var fruit = "apple";
// At this time, this in function foo points to the window object
// This calling method is completely equivalent to window.foo();
foo(); // "apple"
// Customize an object and point the object's attribute foo to the global function foo
var pack = {
fruit: "orange",
foo : foo
};
// At this time, this in function foo points to the window.pack object
pack.foo(); // "orange"
Global function apply and call can be used to change the pointing of the 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 in foo === pack
foo.apply(pack); // "orange"
Note: The two functions apply and call 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:
// Define a global function
function foo() {
if (this === window) {
console.log("this is window.");
}
}
// The function foo is also an object, so you can define the attribute boo of foo 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 that this in the function points to the object of the calling function
foo.boo(); // this is foo.
// Use apply to change the pointer of this in the function
foo.boo.apply(window); // this is window.