The point of this keyword in JS
This in object-oriented language represents a reference to the current object
But in JavaScript this is not fixed, it will change as the execution environment changes
The execution environment is divided into the following types:
First define a function and learn through examples.
<script>
var person = {
firstName: "John",
lastName : "Doe",
id : 5566,
fullName : function() {
return this.firstName + " " + this.lastName;
}
};
document.getElementById("demo").innerHTML = person.fullName();
</script>
In the method, this represents the object to which the method belongs
- In the method of the object, this points to the object that called the method
- In the example below, this represents the person object.
- The object to which the fullName method belongs is person
Instance
<script>
var person = {
firstName: "John",
lastName : "Doe",
id : 5566,
fullName : function() {
return this.firstName + " " + this.lastName;
}
};
document.getElementById("demo").innerHTML = person.fullName();
</script>
If used alone, this represents the global object
- Use this alone, it points to the global object
- In the browser, window is the global object as [object Window]:
Instance
<script>
var x = this;
document.getElementById("demo").innerHTML = x;
</script>
- In strict mode, if used alone, this also points to the global object
Instance
<script>
"use strict";
var x = this;
document.getElementById("demo").innerHTML = x;
</script>
In the function, this represents the global object
- In the function, the owner of the function is bound to this by default
- In the browser, window is the global object as [object Window]
Instance
<script>
document.getElementById("demo").innerHTML = myFunction();
function myFunction() {
return this;
}
</script>
In functions, in strict mode, this is undefined (undefined)
- In strict mode, the function is not bound to this, and this is undefined at this time.
Instance
<script>
"use strict";
document.getElementById("demo").innerHTML = myFunction();
function myFunction() {
return this;
}
</script>
In the event, this represents the element receiving the event
- In the HTML event handler, this points to the HTML element receiving the event
Instance
<body>
<h2>JavaScript <b>this</b> 关键字</h2>
<button onclick="this.style.display='none'">点我后我就消失了</button>
</body>
apply and call allow to switch the context of function execution, that is, the object bound by this, and this can be referenced to any object.