Four modes of this value in JS
This article mainly shares with the four modes of this value in JS, hoping to help everyone.
1. Function Introduction
Inside each function in JavaScript, except for the declaration In addition to the formal parameters defined when ##, each function also has two additional parameters: <span style="font-size: 14px;"></span>this<span style="font-size: 14px;"></span>
and <span style="font-size: 14px;"></span>arguments<span style="font-size: 14px;"></span>
. <span style="font-size: 14px;"></span>
Parameters<span style="font-size: 14px;"></span>arguments<span style="font-size: 14px;"></span>
is an array type variable. The value in the array is what is passed in when the function is actually called. parameter list. When defining a function, there will be formal parameters of the function <span style="font-size: 14px;"></span>parameters<span style="font-size: 14px;"></span>
. When the function is specifically called, when the actual parameters are <span style="font-size: 14px;"></span>arguments# When the number of <span style="font-size: 14px;"></span>## does not match the number of formal parameters
<span style="font-size: 14px;"></span>parameters<span style="font-size: 14px;"></span>, no runtime error will occur. If there are too many actual parameters, the excess parameter values will be ignored. If there are too few actual parameter values, the missing values will be replaced with
<span style="font-size: 14px;"></span>undefined<span style="font-size: 14px;"></span>. There is no type checking of parameter values when the function is executed, which means that any type of value can be passed to any parameter.
<span style="font-size: 14px;"></span>
<span style="font-size: 14px;"></span>this<span style="font-size: 14px;"></span> is a very important concept in object-oriented programming languages, it refers to specific classes The instance of the object is the specific object itself that comes out of the class
<span style="font-size: 14px;"></span>new<span style="font-size: 14px;"></span>. But the value of
<span style="font-size: 14px;"></span>this<span style="font-size: 14px;"></span> in JavaScript depends on the calling mode. There are four calling modes in JavaScript: method calling mode, function calling mode, constructor calling mode and apply calling mode.
<span style="font-size: 14px;"></span>
<span style="font-size: 14px;"></span>
#When a function is defined on an attribute of an object, then we call the function the object a method. When this method is called, this inside the function points to the object. The example is as follows:<span style="font-size: 14px;">var obj = { value: 1,<br/> add: function() { // 这里的 this 是绑定在 obj 这个对象上的<br/> this.value += 1; return this.value;<br/> }<br/>};<br/>console.info(obj.add()); // 2console.info(obj.add()); // 3<br/></span>
obj.add<span style="font-size: 14px;"></span>method You can access your own object through
<span style="font-size: 14px;"></span>this<span style="font-size: 14px;"></span>
<span style="font-size: 14px;"></span>obj<span style="font-size: 14px;"></span>, so it can access it from the object Get the value or modify the object.
This binding to the object occurs when the method is called. Methods that can obtain the context of the object to which they belong through this<span style="font-size: 14px;"></span> are called public methods.
<span style="font-size: 14px;"></span>
<span style="font-size: 14px;"></span>
When a function is not a property of an object, it is called as a function.<span style="font-size: 14px;"></span>
Example 1<span style="font-size: 14px;"></span>
<span style="font-size: 14px;">var a = 1;var add = function(b) {<br/> // 这里的 this 是绑定在全局作用于 window 上的<br/> return this.a + b;<br/>};<br/>console.info(add(2)); // 3<br/></span>Copy after login
Example 2It can be seen from the above two examples that when calling a function in this mode, this is bound to the global object. If we reason according to the<span style="font-size: 14px;"></span>
<span style="font-size: 14px;">var a = 1;var obj = {<br/> a: 2,<br/> add: function(b) {<br/><br/> var innerAdd = function(innerB) {<br/> // 这里的 this 绑定的还是 window 对象上的 this<br/> return this.a + innerB;<br/> };<br/> console.info(innerAdd(0)); // 1<br/> // 这里的 this 是绑定在 obj 对象上的<br/> return this.a + b;<br/> }<br/>};<br/>console.info(obj.add(0)); // 2<br/></span>Copy after login
method calling pattern, this here should be bound to the external function, but this design flaw is not unsolvable. We can assign this of the external function to a variable. The following example:
Example 34. Constructor calling mode<span style="font-size: 14px;"></span>
<span style="font-size: 14px;">var a = 1;var obj = {<br/> a: 2,<br/> add: function(b) {<br/> // 将绑定在 obj 对象上的 this 赋值给变量 that<br/> var that = this; var innerAdd = function(innerB) {<br/> // 这里调用的是变量 that,这个 that 是绑定在 obj 对象上的<br/> return that.a + innerB;<br/> };<br/> console.info(innerAdd(0)); // 2<br/> // 这里的 this 是绑定在 obj 对象上的<br/> return this.a + b;<br/> }<br/>};<br/>console.info(obj.add(0)); // 2<br/></span>Copy after login
<span style="font-size: 14px;"></span>
If you call a function with<span style="font-size: 14px;"></span>new<span style="font-size: 14px;"></span>#, then a
# connected to the function will be created internally. ##prototype<span style="font-size: 14px;"> A new object of members, and this will be bound to that new object. </span>
如果函数定义时内部存在<span style="font-size: 14px;">return</span>
关键词,这时return 出去的就是<span style="font-size: 14px;">this</span>
(新创建的对象)。
<span style="font-size: 14px;">// 定义一个 Person 函数(类)var Person = function(name) { // 这里的 this 绑定的就是 new 出来的那个实例对象<br/> this.name = name;<br/>};// 定义 Person 函数(类)的原型对象Person.prototype = {<br/> run: function() { /**<br/> * 这里的 this 并没有绑定在 Person.prototype 对象上<br/> * 而是绑定在 new 出来的那个实例对象上<br/> */<br/> console.info(this.name + '的 run 方法。');<br/> }<br/>};var lily = new Person('lily');<br/>lily.run(); // lily的 run 方法。<br/></span>
提示:一个函数,如果定义的目的就是结合 new 前缀来调用,那它就被称为构造函数。并且按照约定,它们定义的函数名以大写字母开头。
五、apply调用模式
因为JavaScript是一门函数式的面向对象编程语言,所以函数也可以拥有方法,apply就是<span style="font-size: 14px;">Function.prototype</span>
上的一个方法。
apply方法让我们构建一个参数数组传递给调用函数,它还可以容许我们选择this的值。apply方法接受两个参数,第一个是要绑定 this 的值,第二个就是这个函数执行时的实参 参数 数组了。
例一
<span style="font-size: 14px;">var add = function(a, b) {<br/> return a + b;<br/>};var result = add.apply(null, [1, 2]);<br/>console.info(result); // 3<br/></span>
例二
<span style="font-size: 14px;">var obj = {<br/> name: 'obj',<br/> introduction: function() {<br/> console.info('My name is ' + this.name);<br/> }<br/>};<br/>obj.introduction.apply(obj, []); // My name is objvar anotherObj = {<br/> name: 'anotherObj'};<br/><br/>obj.introduction.apply(anotherObj, []); // My name is anotherObj<br/></span>
总结:以上就是JavaScript中用到this的几种情况了,在面向对象中搞清楚this的指向是非常重要的,在JavaScript中也同等重要。
相关推荐:
The above is the detailed content of Four modes of this value in JS. For more information, please follow other related articles on the PHP Chinese website!

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

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

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

What does WeChat Do Not Disturb mode mean? Nowadays, with the popularity of smartphones and the rapid development of mobile Internet, social media platforms have become an indispensable part of people's daily lives. WeChat is one of the most popular social media platforms in China, and almost everyone has a WeChat account. We can communicate with friends, family, and colleagues in real time through WeChat, share moments in our lives, and understand each other’s current situation. However, in this era, we are also inevitably faced with the problems of information overload and privacy leakage, especially for those who need to focus or

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 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

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

Even answering calls in Do Not Disturb mode can be a very annoying experience. As the name suggests, Do Not Disturb mode turns off all incoming call notifications and alerts from emails, messages, etc. You can follow these solution sets to fix it. Fix 1 – Enable Focus Mode Enable focus mode on your phone. Step 1 – Swipe down from the top to access Control Center. Step 2 – Next, enable “Focus Mode” on your phone. Focus Mode enables Do Not Disturb mode on your phone. It won't cause any incoming call alerts to appear on your phone. Fix 2 – Change Focus Mode Settings If there are some issues in the focus mode settings, you should fix them. Step 1 – Open your iPhone settings window. Step 2 – Next, turn on the Focus mode settings

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 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

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
