Table of Contents
Use this
Home Web Front-end Front-end Q&A What does this mean in javascript

What does this mean in javascript

Jun 30, 2021 pm 02:38 PM
javascript this

The Chinese meaning of this is "current; this". It is a pointer variable in JavaScript, which points to the running environment of the current function. When the same function is called in different scenarios, the pointer of this will change, but it will always point to the real caller of the function in which it is located; if there is no caller, this will point to the window.

What does this mean in javascript

The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.

JavaScript The scope of a function is static, but the function call is dynamic. Since functions can be executed in different running environments, JavaScript defines the this keyword in the function body to obtain the current running environment.

this is a pointer variable that points to the running environment of the current function.

When the same function is called in different scenarios, the pointer of this may also change, but it will always point to the real caller of the function in which it is located (whoever calls it points to who); if there is no caller, this Just point to the global object window.

Use this

This is automatically generated by the JavaScript engine when executing the function. It is a dynamic pointer that exists within the function and refers to the current calling object. The specific usage is as follows:

this[.属性]
Copy after login

If this does not contain attributes, the current object is passed.

This is flexible in usage and the values ​​it contains are also varied. For example, the following example uses the call() method to continuously change the object this refers to within a function.

var x = "window";  //定义全局变量x,初始化字符串为“window”
function a () {  //定义构造函数a
    this.x = "a";  //定义私有属性x,初始化字符a
}
function b () {  //定义构造函数b
    this.x = "b";  //定义私有属性x,初始化为字符b
}
function c () {  //定义普通函数,提示变量x的值
    console.log(x);
}
function f () {  //定义普通函数,提示this包含的x的值
    console.log(this.x);
}
f();  //返回字符串“window”,this指向window对象
f.call(window);  //返回字符串“window”,指向window对象
f.call(new a());  //返回字符a,this指向函数a的实例
f.call(new b());  //返回字符b,this指向函数b的实例
f.call(c);  //返回undefined,this指向函数c对象
Copy after login

The following is a brief summary of the performance and response strategies of this in 5 common scenarios.

1. Ordinary calls

The following example demonstrates the impact of function references and function calls on this.

var obj = {  //父对象
    name : "父对象obj",
    func : function () {
        return this;
    }
}
obj.sub_obj = {  //子对象
    name : "子对象sub_obj",
    func : obj.func
}
var who = obj.sub_obj.func();
console.log(who.name);  //返回“子对象sub_obj”,说明this代表sub_obj
Copy after login

If you change the func of the sub-object sub_obj to a function call.

obj.sub_obj = {
    name : "子对象sub_obj",
    func : obj.func()  //调用父对象obj的方法func
}
Copy after login

Then this in the function represents the parent object obj where the function is defined.

var who = obj.sub_obj.func;
console.log(who.name);  //返回“父对象obj”,说明this代表父对象obj
Copy after login

2. Instantiation

When calling a function using the new command, this always refers to the instance object.

var obj = {};
obj.func = function () {
    if (this == obj) console.log("this = obj");
    else if (this == window) console.log("this = window");
    else if (this.contructor == arguments.callee) console.log("this = 实例对象");
}
new obj.func;  //实例化
Copy after login

3. Dynamic calling

Use call and apply to force this to point to the parameter object.

function func () {
    //如果this的构造函数等于当前函数,则表示this为实例对象
    if (this.contructor == arguments.callee) console.log("this = 实例对象");
    //如果this等于window,则表示this为window对象
    else if (this == window) console.log("this = window对象");
    //如果this为其他对象,则表示this为其他对象
    else console.log("this == 其他对象 \n this.constructor =" + this.constructor);
}
func();  //this指向window对象
new func();  //this指向实例对象
cunc.call(1);  //this指向数值对象
Copy after login

In the above example, when func() is called directly, this represents the window object. When a function is called using the new command, a new instance object will be created, and this will point to this newly created instance object.

When using the call() method to execute the function func(), since the parameter value of the call() method is the number 1, the JavaScript engine will force the number 1 to be encapsulated into a numerical object, and this will point to this Numeric object.

4. Event processing

In the summary of event processing functions, this always points to the object that triggered the event.

<input type="button" value="测试按钮" />
<script>
    var button = document.getElementsByTagName("put")[0];
    var obj = {};
    obj.func = function () {
        if (this == obj) console.log("this = obj");
        if (this == window) console.log("this = window");
        if (this == button) console.log("this = button");
    }
    button.onclick = obj.func;
</script>
Copy after login

In the above code, this contained in func() no longer points to the object obj, but to the button button, because func() is called after being passed to the button's event handling function. .

If you use the DOM2 level standard to register the event handler function, the procedure is as follows:

if (window.attachEvent) {  //兼容IE模型
    button.attachEvent("onclick", obj.func);
} else {  //兼容DOM标准模型
    button.addEventListener("click", obj.func, true);
}
Copy after login

In the IE browser, this points to the window object and button object, but in the DOM standard browser it only points to button object. Because, in the IE browser, attachEvent() is a method of the window object. When this method is called, this will point to the window object.

In order to solve browser compatibility issues, you can call the call() or apply() method to force the method func() to be executed on the object obj to avoid the problem of different browsers parsing this differently.

if (window.attachEvent) {
    button.attachEvent("onclick", function () {  //用闭包封装call()方法强制执行func()
        obj.func.call(obj);
    });
} else {
    button.attachEventListener("onclick", function () {
        obj.func.call(obj);
    }, true);
}
Copy after login

When executed again, this contained in func() always points to the object obj.

5. Timer

Use the timer to call the function.

var obj = {};
obj.func = function () {
    if (this == obj) console.log("this = obj");
    else if (this == window) console.log("this = window对象");
    else if (this.constructor == arguments.callee) console.log("this = 实例对象");
    else console.log("this == 其他对象 \n this.constructor =" + this.constructor);
}
setTimeOut(obj.func, 100);
Copy after login

In IE, this points to the window object and button object. The specific reason is the same as the attachEvent() method explained above. In DOM-compliant browsers, this points to the window object, not the button object.

Because the method setTimeOut() is executed in the global scope, this points to the window object. To resolve browser compatibility issues, you can use the call or apply methods.

setTimeOut (function () {
    obj.func.call(obj);
}, 100);
Copy after login

【Related recommendations: javascript learning tutorial

The above is the detailed content of What does this mean in javascript. For more information, please follow other related articles on the PHP Chinese website!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

How to use insertBefore in javascript How to use insertBefore in javascript Nov 24, 2023 am 11:56 AM

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

JavaScript and WebSocket: Building an efficient real-time image processing system JavaScript and WebSocket: Building an efficient real-time image processing system Dec 17, 2023 am 08:41 AM

JavaScript is a programming language widely used in web development, while WebSocket is a network protocol used for real-time communication. Combining the powerful functions of the two, we can create an efficient real-time image processing system. This article will introduce how to implement this system using JavaScript and WebSocket, and provide specific code examples. First, we need to clarify the requirements and goals of the real-time image processing system. Suppose we have a camera device that can collect real-time image data

See all articles