5 minutes to understand the usage of this in JavaScript_javascript skills
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
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:
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.
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.
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