Introduction to the use of this variable in JS_Basic knowledge
The use of this in JavaScript
The this variable is an elusive keyword in JavaScript. This is very powerful. Fully understanding the relevant knowledge of this will help us write object-oriented JavaScript programs. Be able to do it with ease.
The most important thing about this variable is to be able to clarify which object this refers to. Maybe a lot of information has its own explanation, but some concepts are a bit complicated. My understanding is: first analyze which object the function in which this is located is called as a method, then the object is the object referenced by this.
Example 1,
var obj = {};
obj.x = 100;
obj.y = function(){ alert( this.x ); };
obj.y(); //Pop up 100
This code is very easy to understand. When obj.y() is executed, the function is called as a method of the object obj, so this in the function body points to the obj object. So 100 will pop up.
Example 2,
var checkThis = function(){
alert( this.x);
};
var x = 'this is a property of window';
var obj = {};
obj.x = 100;
obj.y = function(){ alert( this.x ); };
obj.y( ); //Pop up 100
checkThis(); //Pop up 'this is a property of window'
Why does 'this is a property of window' pop up here? Maybe Somewhat confusing. There is a rule in JavaScript variable scope that "global variables are properties of the window object". When checkThis() is executed, it is equivalent to window.checkThis(). Therefore, at this time, the point of the this keyword in the checkThis function becomes the window object, and because the window object has another x attribute ('thisis a property of window' ), so 'this is a property of window' will pop up.
The above two examples are relatively easy to understand, because as long as you determine which object the current function is called as a method (which object is called), you can easily determine the current this variable. Point.
this.x and apply(), call()
Through call and apply, you can redefine the execution environment of the function, that is, the point of this, which is very commonly used in some applications.
Example 3: call()
function changeStyle( type , value ){
this.style[ type ] = value;
}
var one = document.getElementByIdx( 'one' );
changeStyle.call( one , 'fontSize' , '100px' );
changeStyle('fontSize' , '300px'); //An error occurred because this in changeStyle refers to window object, and window has no style attribute.
Note that there are three parameters in changeStyle.call(). The first parameter is used to specify which object the function will be called. One is specified here, which means that the changeStyle function will be called by one, so this point in the function body is the one object. The second and third parameters correspond to the two formal parameters type and value in the changeStyle function. The most common effect we see is that the font of Dom element one becomes 20px.
Example 4: apply()
function changeStyle( type , value ){
this.style[ type ] = value;
}
var one = document.getElementByIdx( 'one' );
changeStyle.apply( one , ['fontSize' , '100px' ]);
changeStyle('fontSize' , '300px'); //An error occurred, the reason is the same as Example 3
The usage of apply is roughly the same as call, with only one difference. apply only accepts two parameters. The first parameter is the same as call. The second parameter must be an array. The elements in the array correspond to functions. formal parameters.
Meaningless (weird) use of this
Example 5:
var obj = {
x : 100,
y : function(){
setTimeout(
function(){ alert(this.x); } //This here points to the window object, not the obj we expect, so undefined will pop up
, 2000);
}
};
obj.y();
How to achieve the desired effect
var obj = {
x : 100,
y : function(){
var that = this;
setTimeout(
function() { alert(that.x); }
, 2000);
}
};
obj.y(); //pop 100
This in the event listening function
var one = document.getElementByIdx( 'one' );
one.onclick = function(){
alert( this.innerHTML ); //this points to the one element , this is very simple..
};
Note: Global variables in js will be dynamically added to the instance window of Window as its attributes.
This is a keyword in js. The value of this will change as the function is used in different situations. But there is always a principle, that is, this refers to the object that calls the function.
1. Pure function call.
function test() {
this.x = 1;
alert(x);
}
test();
In fact, this here is the global variable. You can clearly understand by looking at the following example. In fact, this is the global object Global.
var x = 1;
function test() {
alert(this.x);
}
test();//1
var x = 1;
function test() {
this.x = 0;
}
test();
alert(x);//0
2. As a method call, then this refers to the superior object.
function test() {
alert(this. x);
}
var o = {};
o.x = 1;
o.m = test;
o.m(); //1
3. Called as a constructor. The so-called constructor function is to generate a new object. At this time, this refers to this object.
function test() {
this.x = 1;
}
var o = new test();
alert(o.x);//1
4. apply calls
this points to is the first parameter in apply.
var x = 0;
function test() {
alert(this.x);
}
var o = {};
o.x = 1;
o.m = test;
o.m.apply(); / /0
o.m.apply(o);//1
When apply has no parameters, it is represented as a global object. So the value is 0.

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



How to use JS and Baidu Map to implement map pan function Baidu Map is a widely used map service platform, which is often used in web development to display geographical information, positioning and other functions. This article will introduce how to use JS and Baidu Map API to implement the map pan function, and provide specific code examples. 1. Preparation Before using Baidu Map API, you first need to apply for a developer account on Baidu Map Open Platform (http://lbsyun.baidu.com/) and create an application. Creation completed

Essential tools for stock analysis: Learn the steps to draw candle charts in PHP and JS. Specific code examples are required. With the rapid development of the Internet and technology, stock trading has become one of the important ways for many investors. Stock analysis is an important part of investor decision-making, and candle charts are widely used in technical analysis. Learning how to draw candle charts using PHP and JS will provide investors with more intuitive information to help them make better decisions. A candlestick chart is a technical chart that displays stock prices in the form of candlesticks. It shows the stock price

Face detection and recognition technology is already a relatively mature and widely used technology. Currently, the most widely used Internet application language is JS. Implementing face detection and recognition on the Web front-end has advantages and disadvantages compared to back-end face recognition. Advantages include reducing network interaction and real-time recognition, which greatly shortens user waiting time and improves user experience; disadvantages include: being limited by model size, the accuracy is also limited. How to use js to implement face detection on the web? In order to implement face recognition on the Web, you need to be familiar with related programming languages and technologies, such as JavaScript, HTML, CSS, WebRTC, etc. At the same time, you also need to master relevant computer vision and artificial intelligence technologies. It is worth noting that due to the design of the Web side

How to use PHP and JS to create a stock candle chart. A stock candle chart is a common technical analysis graphic in the stock market. It helps investors understand stocks more intuitively by drawing data such as the opening price, closing price, highest price and lowest price of the stock. price fluctuations. This article will teach you how to create stock candle charts using PHP and JS, with specific code examples. 1. Preparation Before starting, we need to prepare the following environment: 1. A server running PHP 2. A browser that supports HTML5 and Canvas 3

How to use JS and Baidu Maps to implement the map heat map function Introduction: With the rapid development of the Internet and mobile devices, maps have become a common application scenario. As a visual display method, heat maps can help us understand the distribution of data more intuitively. This article will introduce how to use JS and Baidu Map API to implement the map heat map function, and provide specific code examples. Preparation work: Before starting, you need to prepare the following items: a Baidu developer account, create an application, and obtain the corresponding AP

Overview of how to use JS and Baidu Maps to implement map click event processing: In web development, it is often necessary to use map functions to display geographical location and geographical information. Click event processing on the map is a commonly used and important part of the map function. This article will introduce how to use JS and Baidu Map API to implement the click event processing function of the map, and give specific code examples. Steps: Import the API file of Baidu Map. First, import the file of Baidu Map API in the HTML file. This can be achieved through the following code:

With the rapid development of Internet finance, stock investment has become the choice of more and more people. In stock trading, candle charts are a commonly used technical analysis method. It can show the changing trend of stock prices and help investors make more accurate decisions. This article will introduce the development skills of PHP and JS, lead readers to understand how to draw stock candle charts, and provide specific code examples. 1. Understanding Stock Candle Charts Before introducing how to draw stock candle charts, we first need to understand what a candle chart is. Candlestick charts were developed by the Japanese

How to use JS and Baidu Maps to implement map polygon drawing function. In modern web development, map applications have become one of the common functions. Drawing polygons on the map can help us mark specific areas for users to view and analyze. This article will introduce how to use JS and Baidu Map API to implement map polygon drawing function, and provide specific code examples. First, we need to introduce Baidu Map API. You can use the following code to import the JavaScript of Baidu Map API in an HTML file
