Home >Web Front-end >JS Tutorial >5 minutes to understand the usage of this in JavaScript_javascript skills

5 minutes to understand the usage of this in JavaScript_javascript skills

WBOY
WBOYOriginal
2016-05-16 17:16:351019browse

Foreword
There are many more detailed introductions to the usage of this in JavaScript on the Internet. You can refer to the reference learning materials and the Internet in this article. This article combines collection and collection from the Internet to try to explain the usage of this in JavaScript in a simple way. I hope it will be helpful to everyone's quick understanding of the usage of this in JavaScript.
Text
1. This usage example

Copy code The code is as follows:

window.color = “red”;
var o = { color: “blue” };
function sayColor(){
alert(this.color);
}
sayColor() ; //"red"
o.sayColor = sayColor;
o.sayColor(); //"blue"

2. The usage of this is easy to understand
Where this points to :
The environment in which this runs (the context object), or simply understood as: the current scope when the function where this is located is called.
A piece of example code will be understood immediately:
Copy code The code is as follows:

var fun = function() {
console.log(this);
}
fun();// console: window, the execution context of fun is window, that is, when the function (fun()) where this is located is called The current scope of is window.
new fun();//console: fun, the execution context of fun is within the fun object, that is, the current scope when the function (fun()) in which this is located is called, is within the fun object.

3. A special case of this usage
(1) Case:
Copy code The code is as follows:




Click this After pressing the button, you will find that the value of the button has not changed.
Reason: When this code is running, this points to the window object.
Copy code The code is as follows:




After clicking this button, the program can execute normally.
(2) Reason explanation:
Copy code The code is as follows:




The output obtained is:
Copy the code The code is as follows:

function demo() {
this.value = Math.random();
}


Copy code The code is as follows:




The output obtained is:
Copy the code The code is as follows:

function onclick( ) {
demo();
}
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn