search
HomeWeb Front-endJS TutorialFour modes of this value in JS

Four modes of this value in JS

Feb 24, 2018 pm 02:22 PM
javascriptthismodel


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>

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>

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>

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>

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>

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

总结:以上就是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
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
The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js Streams with TypeScriptNode.js Streams with TypeScriptApr 30, 2025 am 08:22 AM

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

Python vs. JavaScript: Performance and Efficiency ConsiderationsPython vs. JavaScript: Performance and Efficiency ConsiderationsApr 30, 2025 am 12:08 AM

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

The Origins of JavaScript: Exploring Its Implementation LanguageThe Origins of JavaScript: Exploring Its Implementation LanguageApr 29, 2025 am 12:51 AM

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

Behind the Scenes: What Language Powers JavaScript?Behind the Scenes: What Language Powers JavaScript?Apr 28, 2025 am 12:01 AM

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The Future of Python and JavaScript: Trends and PredictionsThe Future of Python and JavaScript: Trends and PredictionsApr 27, 2025 am 12:21 AM

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Python vs. JavaScript: Development Environments and ToolsPython vs. JavaScript: Development Environments and ToolsApr 26, 2025 am 12:09 AM

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Is JavaScript Written in C? Examining the EvidenceIs JavaScript Written in C? Examining the EvidenceApr 25, 2025 am 12:15 AM

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

See all articles

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

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment