Home Web Front-end JS Tutorial A code example for understanding values ​​and references in JavaScript parameter passing

A code example for understanding values ​​and references in JavaScript parameter passing

Mar 06, 2017 pm 02:24 PM

Value and reference are common topics in various programming languages, and js is no exception.

I will analyze the actual running process of an example and share with you my understanding of values ​​and references in js parameter passing.

Refer to the two classifications of data types on the official website. This article refers to these two classifications as basic types (boolean, null, undefined, string, number, symbol) and object types.

First, use an example to demonstrate the application of parameter passing:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

var obj = {};

obj.inner = 10;

 

var num = 10;

var str = 'Hello';

var boo = true;

var oth = null;

var und = undefined;

var sym = Symbol('foo');

 

function passingobject(myobj){

    myobj.inner  = 1 + myobj.inner ;

}

 

function passingvalue(myvalue){

  switch(typeof myvalue){

    case 'number':

        myvalue = myvalue + 1;

        break;

      case 'string':

        myvalue = 'I am a new string now!';

        break;

      case 'boolean':

        myvalue= false;

        break;

      default:

        myvalue = 'Null, Undefined, or Symbol';

     }

  }

 

  console.log("before num = " + num);  // before num = 10

  passingvalue(num);

  console.log("after num = " + num);  // after num = 10

  console.log("before str = " + str); // before str = Hello

  passingvalue(str);

  console.log("after str = " + str);  // after str = Hello

  console.log("before boo = " + boo); // before boo = true

  passingvalue(boo);

  console.log("after boo = " + boo);  // after boo = false

  console.log("before oth = " + oth); // before oth = null

  passingvalue(oth);

  console.log("after oth = " + oth);  // after oth = null

  console.log("before und = " + und); // before und = undefined

  passingvalue(und);

  console.log("after und = " + und);  // after und = undefined

  console.log(sym); // Symbol(foo)

  passingvalue(sym);

  console.log(sym); // Symbol(foo)

  console.log("before obj.inner = " + obj.inner); // before obj.inner = 10

  passingobject(obj); // after obj.inner = 11

  console.log("after obj.inner = " + obj.inner);

Copy after login

It seems that the following two conclusions can be drawn from the results of example 1:

1. The data type passed It is a basic type (number, string boolean, null, undefined, symbol). During the parameter passing process, the operation of the passed value within the function does not affect the original value.

2. The data type passed is object. During the parameter passing process, the operation on the passed value inside the function will cause the original value to change.

However, are there any other special circumstances?

There is a usage that is very hotly discussed on stackoverflow, which goes against conclusion 2. example 2.

Example quoted from: http://www.php.cn/

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

1 function changeStuff(a, b, c)

 2 {

 3   a = a * 10;

 4   b.item = "changed";

 5   c = {item: "changed"};

 6 }

 7

 8 var num = 10;

 9 var obj1 = {item: "unchanged"};

10 var obj2 = {item: "unchanged"};

11

12 console.log(obj1.item); // unchanged

13 console.log(obj2.item); // unchanged

14 changeStuff(num, obj1, obj2);

15 console.log(obj1.item); // changed

16 console.log(obj2.item); // unchanged

Copy after login

In example 2, obj2.item is not changed by the function changeStuff. The values ​​of b and c are also changed internally in changeStuff. Why is obj1 changed (L15) but obj2 not changed?

I use the execution context of js to explain this phenomenon, as shown in the figure.

During the running of js, the editor dynamically generates an execution context (execution context). In example 2, the global execution context and the changeStuff execution context are first generated.

When changeStuff(num, obj1, obj2) is executed, a, b, c point to the parameters num, obj1, obj2, a and num point to 10, b and obj1 point to the same value, and c and obj2 point to same value.

When executing step 1, reassign a to 10 times the value before a was assigned. From now on, a has nothing to do with num.

When executing step 2, reassign the item attribute of the value pointed to by b. This assignment only changes the value of item, while obj1 and b still point to the same value.

When step 3 is executed, c is reassigned. From then on, c has nothing to do with obj2. Therefore, even if c has an attribute called item, it has its own value with the item attribute of obj2, and it does not affect obj2. item.

In other words, during the js function parameter passing process, if the parameters are reassigned inside the function, this assignment process will not affect the value of the original variable.

This also well explains the phenomenon that basic type parameter variables (Conclusion 1) will not be affected. Every change of basic type parameter variables is a new assignment and will not affect the original variables. .

Summary

In js function transfer, when basic type (number, string, boolean, null, undefined, symbol) variables are passed as parameters, the function internal Any operation on the parameters will not change the value of the variable.

When an object type variable is passed as a parameter, the operation on the parameter inside the function will affect the value of the variable, Unless the parameter is reassigned (any type of value) inside the function.

Thank you!

Feel free to contact me if you have any question!

The above is the content of the code example for understanding the value and reference in JavaScript parameter passing. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!


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)

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

Best practices for optimizing Golang function parameter passing performance Best practices for optimizing Golang function parameter passing performance Apr 13, 2024 am 11:15 AM

In order to optimize Go function parameter passing performance, best practices include: using value types to avoid copying small value types; using pointers to pass large value types (structures); using value types to pass slices; and using interfaces to pass polymorphic types. In practice, when passing large JSON strings, passing the data parameter pointer can significantly improve deserialization performance.

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 get HTTP status code in JavaScript the easy way How to get HTTP status code in JavaScript the easy way Jan 05, 2024 pm 01:37 PM

Introduction to the method of obtaining HTTP status code in JavaScript: In front-end development, we often need to deal with the interaction with the back-end interface, and HTTP status code is a very important part of it. Understanding and obtaining HTTP status codes helps us better handle the data returned by the interface. This article will introduce how to use JavaScript to obtain HTTP status codes and provide specific code examples. 1. What is HTTP status code? HTTP status code means that when the browser initiates a request to the server, the service

What is the parameter passing method for PHP functions? What is the parameter passing method for PHP functions? Apr 10, 2024 am 11:06 AM

There are two ways to pass parameters in PHP: call by value (the parameter is passed as a copy of the value, modification within the function does not affect the original variable) and passing by reference (the address of the parameter is passed, modification within the function will affect the original variable), when the original variable needs to be modified Use reference passing when calculating the shopping cart total price, which requires reference passing to calculate correctly.

JavaScript and WebSocket: Building an efficient real-time search engine JavaScript and WebSocket: Building an efficient real-time search engine Dec 17, 2023 pm 10:13 PM

JavaScript and WebSocket: Building an efficient real-time search engine Introduction: With the development of the Internet, users have higher and higher requirements for real-time search engines. When searching with traditional search engines, users need to click the search button to get results. This method cannot meet users' needs for real-time search results. Therefore, using JavaScript and WebSocket technology to implement real-time search engines has become a hot topic. This article will introduce in detail the use of JavaScript

How to pass parameters to PHP function? How to pass parameters to PHP function? Apr 10, 2024 pm 05:21 PM

PHP functions can pass values ​​through parameters, which are divided into pass by value and pass by reference: pass by value: modification of parameters within the function will not affect the original value; pass by reference: modification of parameters within the function will affect the original value. In addition, arrays can also be passed as parameters for operations such as calculating the sum of data.

See all articles