Home > Web Front-end > JS Tutorial > Understand the usage of this in JavaScript in 5 minutes

Understand the usage of this in JavaScript in 5 minutes

高洛峰
Release: 2016-11-26 14:27:26
Original
1119 people have browsed it

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 Internet collection and attempts 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
[javascript]
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:
this running environment (the context object) , or simply understood as: the current scope when the function where this is located is called.
Immediately understand a piece of example code:
[javascript]
var fun = function() {
  console.log(this);
}
fun();// console: window, the execution context of fun is window, which is where this is The current scope when the function (fun()) is called is window.
new fun();//console: fun, the execution context of fun is within the fun object, that is, the current scope when this function (fun()) is called is within the fun object.
3. A special case of this usage
(1) case:
[html]

< ;script type="text/javascript">
function demo() {
this.value = Math.random();
}

After clicking this button, you will find that the value of the button is not Change.
Reason: When this code is running, this points to the window object.
[html]


After clicking this button, the program can execute normally.
(2) Reason explanation:
[html]


The resulting output is:
function demo() {
this.value = Math.random();
}

[html]


The output obtained is:
function onclick() {
demo();
}


Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template