Table of Contents
五、apply调用模式" >五、apply调用模式
Home Web Front-end JS Tutorial Four modes of this value in JS

Four modes of this value in JS

Feb 24, 2018 pm 02:22 PM
javascript this model


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>

Parameters

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

2. Method calling mode

<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>
Copy after login

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>

3. Function calling mode

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

<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

It 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

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 3

<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

4. Constructor calling mode

<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 + &#39;的 run 方法。&#39;);<br/>  }<br/>};var lily = new Person(&#39;lily&#39;);<br/>lily.run(); // lily的 run 方法。<br/></span>
Copy after login

提示:一个函数,如果定义的目的就是结合 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>
Copy after login

例二

<span style="font-size: 14px;">var obj = {<br/>  name: &#39;obj&#39;,<br/>  introduction: function() {<br/>    console.info(&#39;My name is &#39; + this.name);<br/>  }<br/>};<br/>obj.introduction.apply(obj, []); // My name is objvar anotherObj = {<br/>  name: &#39;anotherObj&#39;};<br/><br/>obj.introduction.apply(anotherObj, []); // My name is anotherObj<br/></span>
Copy after login

总结:以上就是JavaScript中用到this的几种情况了,在面向对象中搞清楚this的指向是非常重要的,在JavaScript中也同等重要。

相关推荐:

javascript函数中的this的四种绑定形式

JS中的this、apply、call、bind实例分享

html的标签中的this应该如何使用

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!

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)

What does WeChat's Do Not Disturb mode do? What does WeChat's Do Not Disturb mode do? Feb 23, 2024 pm 10:48 PM

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

Do Not Disturb Mode Not Working in iPhone: Fix Do Not Disturb Mode Not Working in iPhone: Fix Apr 24, 2024 pm 04:50 PM

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

See all articles