js值传递和引用传递

20220601超简单百度地图街景图片爬取+绿视率计算 真的不难咯。 阅读详情
Previous Page
Next Page

3.15. By Value Versus by Reference

In JavaScript, as in all programming languages, you can manipulate a data value in three important ways.[*] First, you can copy it. For example, you might assign it to a new variable. Second, you can pass it as an argument to a function or method. Third, you can compare it with another value to see whether the two values are equal. To understand any programming language, you must understand how these three operations are performed in that language.

[*] This section covers advanced material, which you may want to skip on your first reading.

There are two fundamentally distinct ways to manipulate data values. These techniques are called by value and by reference. When a datum is manipulated by value, it is the value of the datum that matters. In an assignment, a copy of the actual value is made, and that copy is stored in a variable, object property, or array element; the copy and the original are two totally independent values that are stored separately. When a datum is passed by value to a function, a copy of the datum is passed to the function; if the function modifies the value, the change affects only the function's copy of the datumit does not affect the original datum. Finally, when a datum is compared by value to another datum, the two distinct pieces of data must represent exactly the same value (which usually means that a byte-by-byte comparison finds them to be equal).

The other way to manipulate a value is by reference. With this technique, there is only one actual copy of the value; references to that value are manipulated.[] If a value is manipulated by reference, variables do not hold that value directly; they hold only references to it. It is these references that are copied, passed, and compared. So, in an assignment made by reference, it is the reference to the value that is assigned, not a copy of the value and not the value itself. After the assignment, the new variable refers to the same value that the original variable refers to. Both references are equally valid, and both can be used to manipulate the value; if the value is changed through one reference, that change also appears through the original reference. The situation is similar when a value is passed to a function by reference. A reference to the value is passed to the function, and the function can use that reference to modify the value itself; any such modifications are visible outside the function. Finally, when a value is compared to another by reference, the two references are compared to see if they refer to the same unique copy of a value; references to two distinct values that happen to be equivalent (i.e., consist of the same bytes) are not treated as equal.

[] C programmers and anyone else familiar with the concept of pointers should understand the idea of a reference in this context. Note, however, that JavaScript does not support pointers.

These are two very different ways of manipulating values, and they have important implications that you should understand. Table 3-4 summarizes these implications. This discussion of manipulating data by value and by reference has been a general one, but the distinctions apply to all programming languages. The sections that follow explain how these distinctions apply specifically to JavaScript; they discuss which datatypes are manipulated by value and which are manipulated by reference.

Table 3-4. By value versus by reference

By value

By reference

Copy

The value is actually copied; there are two distinct, independent copies.

Only a reference to the value is copied. If the value is modified through the new reference, that change is also visible through the original reference.

Pass

A distinct copy of the value is passed to the function; changes to it have no effect outside the function.

A reference to the value is passed to the function. If the function modifies the value through the passed reference, the modification is visible outside the function.

Compare

Two distinct values are compared (often byte by byte) to see if they are the same value.

Two references are compared to see if they refer to the same value. Two references to distinct values are not equal, even if the two values consist of the same bytes.


3.15.1. Primitive Types and Reference Types

The basic rule in JavaScript is this: primitive types are manipulated by value, and reference types, as the name suggests, are manipulated by reference. Numbers and booleans are primitive types in JavaScriptprimitive because they consist of nothing more than a small, fixed number of bytes that are easily manipulated at the low levels of the JavaScript interpreter. Objects, on the other hand, are reference types. Arrays and functions, which are specialized types of objects, are therefore also reference types. These datatypes can contain arbitrary numbers of properties or elements, so they cannot be manipulated as easily as fixed-size primitive values can. Since object and array values can become quite large, it doesn't make sense to manipulate these types by value, because this could involve the inefficient copying and comparing of large amounts of memory.

What about strings? A string can have an arbitrary length, so it would seem that strings should be reference types. In fact, though, they are usually considered primitive types in JavaScript simply because they are not objects. Strings don't actually fit into the primitive-versus-reference type dichotomy. I'll explain more about strings and their behavior a little later.

The best way to explore the differences between data manipulation by value and by reference is through example. Study the following examples carefully, paying attention to the comments. Example 3-1 copies, passes, and compares numbers. Since numbers are primitive types, this example illustrates data manipulation by value.

Example 3-1. Copying, passing, and comparing by value

// First we illustrate copying by value
var n = 1;  // Variable n holds the value 1
var m = n;  // Copy by value: variable m holds a distinct value 1

// Here's a function we'll use to illustrate passing by value
// As we'll see, the function doesn't work the way we'd like it to
function add_to_total(total, x)
{
    total = total + x;  // This line changes only the internal copy of total
}

// Now call the function, passing the numbers contained in n and m by value.
// The value of n is copied, and that copied value is named total within the
// function. The function adds a copy of m to that copy of n. But adding
// something to a copy of n doesn't affect the original value of n outside
// of the function. So calling this function doesn't accomplish anything.
add_to_total(n, m);

// Now, we'll look at comparison by value.
// In the following line of code, the literal 1 is clearly a distinct numeric
// value encoded in the program. We compare it to the value held in variable
// n. In comparison by value, the bytes of the two numbers are checked to
// see if they are the same.
if (n == 1) m = 2;  // n contains the same value as the literal 1; m is now 2

Now, consider Example 3-2. This example copies, passes, and compares an object. Since objects are reference types, these manipulations are performed by reference. This example uses Date objects, which you can read more about in Part III.

Example 3-2. Copying, passing, and comparing by reference

// Here we create an object representing the date of Christmas, 2007
// The variable xmas contains a reference to the object, not the object itself
var xmas = new Date(2007, 11, 25);
// When we copy by reference, we get a new reference to the original object
var solstice = xmas;  // Both variables now refer to the same object value

// Here we change the object through our new reference to it
solstice.setDate(21);

// The change is visible through the original reference, as well
xmas.getDate( );  // Returns 21, not the original value of 25

// The same is true when objects and arrays are passed to functions.
// The following function adds a value to each element of an array.
// A reference to the array is passed to the function, not a copy of the array.
// Therefore, the function can change the contents of the array through
// the reference, and those changes will be visible when the function returns.
function add_to_totals(totals, x)
{
    totals[0] = totals[0] + x;
    totals[1] = totals[1] + x;
    totals[2] = totals[2] + x;
}

// Finally, we'll examine comparison by reference.
// When we compare the two variables defined above, we find they are
// equal, because they refer to the same object, even though we were trying
// to make them refer to different dates:
(xmas == solstice)  // Evaluates to true

// The two variables defined next refer to two distinct objects, both
// of which represent exactly the same date.
var xmas = new Date(2007, 11, 25);
var solstice_plus_4 = new Date(2007, 11, 25);

// But, by the rules of "compare by reference," distinct objects are not equal!
(xmas != solstice_plus_4)  // Evaluates to true

Before we leave the topic of manipulating objects and arrays by reference, let's clear up a point of nomenclature. The phrase "pass by reference" can have several meanings. To some readers, the phrase refers to a function-invocation technique that allows a function to assign new values to its arguments and to have those modified values visible outside the function. This is not the way the term is used in this book. Here, I mean simply that a reference to an object or arraynot the object itselfis passed to a function. A function can use the reference to modify properties of the object or elements of the array. But if the function overwrites the reference with a reference to a new object or array, that modification is not visible outside the function. Readers familiar with the other meaning of this term may prefer to say that objects and arrays are passed by value, but the value that is passed is actually a reference rather than the object itself. Example 3-3 illustrates this issue.

Example 3-3. References themselves are passed by value

// This is another version of the add_to_totals( ) function. It doesn't
// work, though, because instead of changing the array itself, it tries to
// change the reference to the array.
function add_to_totals2(totals, x)
{
    newtotals = new Array(3);
    newtotals[0] = totals[0] + x;
    newtotals[1] = totals[1] + x;
    newtotals[2] = totals[2] + x;
    totals = newtotals;  // This line has no effect outside of the function
}

3.15.2. Copying and Passing Strings

As mentioned earlier, JavaScript strings don't fit neatly into the primitive-versus-reference type dichotomy. Since strings are not objects, it is natural to assume that they are primitive. If they are primitive types, then by the rules given above, they should be manipulated by value. But since strings can be arbitrarily long, it would seem inefficient to copy, pass, and compare them byte by byte. Therefore, it would also be natural to assume that strings are implemented as reference types.

Instead of making assumptions about strings, let's write some JavaScript code to experiment with string manipulation. If strings are copied and passed by reference, you should be able to modify the contents of a string through the reference stored in another variable or passed to a function.

When setting out to write the code to perform this experiment, however, you'll run into a major stumbling block: there is no way to modify the contents of a string. The charAt( ) method returns the character at a given position in a string, but there is no corresponding setCharAt( ) method. This is not an oversight. JavaScript strings are intentionally immutablethat is, there is no JavaScript syntax, method, or property that allows you to change the characters in a string.

Since strings are immutable, the original question is moot: there is no way to tell whether strings are passed by value or by reference. You can assume that, for efficiency, JavaScript is implemented so that strings are passed by reference, but in actuality it doesn't matter, because it has no practical bearing on the code you write.

3.15.3. Comparing Strings

Despite the fact that you cannot determine whether strings are copied and passed by value or by reference, you can write JavaScript code to determine whether they are compared by value or by reference. Example 3-4 shows the code that can make this determination.

Example 3-4. Are strings compared by value or by reference?

// Determining whether strings are compared by value or reference is easy.
// We compare two clearly distinct strings that happen to contain the same
// characters. If they are compared by value they will be equal, but if they
// are compared by reference, they will not be equal:
var s1 = "hello";
var s2 = "hell" + "o";
if (s1 == s2) document.write("Strings compared by value");

This experiment demonstrates that strings are compared by value. This may be surprising to some programmers. In C, C++, and Java, strings are reference types and are compared by reference. If you want to compare the actual contents of two strings, you must use a special method or function. JavaScript, however, is a higher-level language and recognizes that when you compare strings, you most often want to compare them by value. Thus, despite the fact that, for efficiency, JavaScript strings are (presumably) copied and passed by reference, they are compared by value.

3.15.4. By Value Versus by Reference: Summary

Table 3-5 summarizes the way that the various JavaScript types are manipulated.

Table 3-5. Datatype manipulation in JavaScript

Type

Copied by

Passed by

Compared by

number

Value

Value

Value

boolean

Value

Value

Value

string

Immutable

Immutable

Value

object

Reference

Reference

Reference



Previous Page
Next Page
SAP_SD模块更改销售订单定价简介 方式优点缺点适用场景MASS简单,无需开发不能触发重新定价逻辑修改特定字段BDC (VA02)可模拟人工操作维护复杂,速度慢少量订单批改稳定、安全需ABAP支持推荐用于批量重新定价VBOF标准重算返利仅适返利类条件返利更新通过本文,我们了解了 SAP 的[SAP_SD模块更改销售订单定价]的基本概念和应用方法。希望这些信息能帮助您在实际工作中更好地使用 SAP 系统,提高工作效率和管理水平。更多SAP文章请点击更多SAP文章更新,大家一起学习进步!!! 阅读详情

相关推荐

VMware ESXI 7.0实战:4T硬盘RAID1配置与性能调优全记录

本文详细记录了在VMware ESXI 7.0环境下,为Dell服务器配置两块4T硬盘组建RAID1并进行深度性能调优的全过程。文章重点解析了RAID控制器写入策略(Write-Back with BBU)、读取策略(Read-Ahead)的关键选择,并深入探讨了在ESXI虚拟机层面通过选用PVSCSI控制器、调整虚拟磁盘缓存策略(scsiX:Y.caching)等技巧,以最大化满足数据分析等IO密集型工作负载的需求,最终实现性能的显著提升。

gaochao的博客 259

JS参数传递(值传递和引用传递)

前端红宝书第一遍看过去之后,相当多的东西都忘记了,第二遍看的时候,也开始注意到一些细节的东西以及理解不到位的地方。书P66 一个加粗框中写到:ECMAScript中所有参数传递都是值,不可能通过引用传递参数当时看过没有怎么仔细想过,一知半解吧,今天理解的更加深一些。当然也是昨天做了个题目就因为这个掉坑里一时没爬出来!访问变量有按值和按引用两种方式,而参数只能按值传递。一、基本数据类型: Numbe...

weixin_39728230的博客 6万+

AutoCAD 2024 LISP实用技巧:自定义快捷命令与高效绘图工具集

本文详细介绍了如何在AutoCAD 2024中部署和使用LISP脚本,打造高效绘图工具集。通过自定义快捷命令,如WFF(超级文字查找替换)、GQT(图层隔离)和LLTJ(智能长度统计),可大幅简化图层管理、文字编辑和测量统计等重复性操作,显著提升绘图效率。

gan8painter的博客 318

java 值传递 js_深入理解JavaScript的值传递和引用传递

JavaScript有5种基本的数据类型,分别是:布尔、null、undefined、String和Number。这些基本类型在赋值的时候是通过值传递的方式。值得注意的是还有另外三种类型: Array、Function和Object,它们通过引用来传递。从底层技术上看,它们三都是对象。基本数据类型如果一个基本的数据类型绑定到某个变量,我们可以认为该变量包含这个基本数据类型的值。var x = 10...

weixin_42443797的博客 364

标准论文参考文献添加方法——Zotero入门使用教程

第一篇论文投出去了,写一下最后一步的参考文献修饰润色吧! 论文的参考文献,即References,是论文的最后一步,相信不管是写毕设论文还是期刊论文都遇到过需要修改参考文献的情况,非常之麻烦。而且参考文献中经常会与生僻奇怪气体出现,一个一个修改非常浪费时间,这里介绍一下一个非常好用的软件Zetero。 第一步:软件的下载安装及绑定Word 尽量使用客户端吧,

MISAYAONE的博客 20万+

科研项目数据抓取:Python爬虫实现与分析

本文详细介绍了如何使用Python爬虫抓取科研项目的数据,涵盖了从目标数据源选择到数据存储与分析的整个过程。通过使用。

2201_76125261的博客 1710

JavaScript的值传递和引用传递

JavaScript有5种基本的数据类型,分别是:布尔、null、undefined、String和Number。这些基本类型在赋值的时候是通过值传递的方式。值得注意的是还有另外三种类型: Array、Function和Object,它们通过引用来传递。从底层技术上看,它们三都是对象。 基本数据类型 如果一个基本的数据类型绑定到某个变量,我们可以认为该变量包含这个基本数据类型的值。 var x = 10; var y = 'abc'; var z = null; 当我们使用=将这些变量赋值到..

qq_21987433的博客 698

Python爬虫实战:基于最新技术栈的政府招标采购数据抓取与分析

对于企业、研究人员和数据分析师来说,能够高效地获取这些数据意味着可以获得宝贵的商业洞察和市场先机。随着反爬技术的不断升级和网站结构的日益复杂,传统的爬虫方法已经难以满足需求。我们将采用Selenium、Playwright等现代浏览器自动化工具,结合Scrapy框架和异步请求库,构建一个能够应对各种反爬措施的强大爬虫系统。Playwright是微软开发的浏览器自动化工具,支持Chromium、WebKit和Firefox,比Selenium更快速、更稳定。

2201_76125261的博客 1311

JavaScript进阶(三) 值传递和引用传递

从C语言开始

Javaallstar的专栏 3955

windows 应用爬虫: exe自动操作

之前写了那么多关于手机和网页爬取,今天就写一期关于exe的爬取,exe的爬取其实也是类似的,一个方式是抓包,还有一个模拟人工界面获取元素数据。抓包肯定是最直接,数据也是最全的, 有些数据不一定会显示在界面上,或者必须通过一定交付方式,才能显示到页面(比如移动鼠标到具体元素上)。本文依旧采用python方式,先说说怎么通过界面方式驱动应用点击和数据获取。

youbingchen的博客 888

Wi-Fi数据帧类别

QoS

1042484520@qq.com(邮箱) 3156

js数组和对象 值传递和引用

js数组和对象分为值传递和引用俩种方式。 对象的值传递 let arr={a:1,b:2} let row =Object.assign({}, arr);//row对象之后的操作不会影响到源对象arr 可能有些人对assign不太了解,看一下下面代码就会知道如何使用 Object.assign(target, ...sources); target 是目标对象 sources 是源对象 ...

木贝西的博客 2297

AI原生SaaS应用的自动化运维体系构建

随着ChatGPT掀起的AI原生应用浪潮,越来越多SaaS(软件即服务)产品开始以"AI优先"的方式设计——从用户交互到核心功能,都深度依赖机器学习模型(如推荐算法、智能客服)、实时数据流(如用户行为分析)和弹性算力(如大模型推理)。这类应用的运维需求与传统SaaS完全不同:传统运维像"修水管",哪里漏了补哪里;AI原生运维则像"照顾会成长的宠物",需要实时感知模型状态、数据变化和流量波动,主动调整资源。

AI天才研究院 1080

JavaScript中栈和堆,值传递和引用传递

JavaScript中栈和堆,值传递和引用传递基本数据类型和引用数据类型栈和堆1. const定义一个变量是不是不可变的2. 数据赋值3. 值传递和引用传递4. 栈内存和堆内存的优缺点 基本数据类型和引用数据类型 在讲什么是栈和堆之前我们首先要知道为什么会有这种东西,我们都知道JavaScript中的数据类型有两种,基本数据类型和引用数据类型。这两种数据有什么区别呢,最大的区别就是基本数据类型是存在栈中,引用类型存在堆中。下面有关于栈和堆的详细讲解 栈和堆 在js引擎中对变量的存储主要有两种位置,堆内存和栈

qq_43742385的博客 381

霍尼韦尔SoftMaster使用说明

霍尼韦尔SoftMaster使用说明

efm32 入门.pdf

本PDF共计22页,介绍的是操作驱动API,下载与否自己斟酌。

js-值传递和引用传递实例代码

js-值传递和引用传递实例代码 <!doctype html> <html> <head> <meta charset="UTF-8"> <title>Document</title> </head> <body> <script> //按

前端博客 645

LinePhone3.2.7(android端最新版本) sip客户端

SIP客户端For android:LinePhone3.2.7(最新版本),官网地址:http://www.linphone.org/

JavaScript 值传递和引用传递

先来看两个个来自于 《JavaScript 高级程序设计》P70-P71 的两个例子。 1.1. 基本类型参数传递 function addTen(num) { num += 10; return num; } var count = 20; var result = addTen(count); alert(count); // 20, 没有变化 alert(result); // 30 书上解释说,JavaScript 参数传递都是按值传参。 所以传递给 addTen 函数的值是 20 这个

猫影 676

JavaScript的值传递和引用传递的区别

前言、JavaScript 数据类型 首先要清楚JavaScript包含哪些数据类型,字符串(String)、数字(Number)、布尔(Boolean)、函数(Function())、数组(Array)、对象(Object)、空(Null)、未定义(Undefined)是JavaScript常见的数据类型。 一、值传递 JavaScript值传递的数据类型:字符串(String)、数字(N...

木易慕翊 1609

c语言值传递和引用传递的区别_JS中函数参数值传递和引用传递

在JavaScript红宝书中说到,“ECMAScript中所有函数的参数都是按值传递的”。理解这个概念先要从JS的堆内存和栈内存说起:栈内存为自动分配的内存空间,它由系统自动释放;堆内存则是动态分配的内存,大小不定也不会自动释放。(很初级的理解,有错误还望指正)JS中的5种基本数据类型Undefined、Null、Boolean、Number 和 String,它们是直接按值存放在栈内存中,可以...

weixin_31493023的博客 303

JavaScript基础之值传递和引用传递

js的值传递和引用(地址)传递 首先总述一下:js的5种基本数据类型 number,string,null,undefined,boolean 在赋值传递时是值传递,js的引用数据类型(object,array,function)进行引用传递,其实底层都是对象。 废话不多说,下面直接上代码 值传递例子: 1 var a = 10; 2 var b = a; 3 b = 5; 4 ...

weixin_33897722的博客 110

JS-堆栈-值传递和引用传递

复制过去的是地址,他们指向同一片内存。

Yous的博客 155

论javascript函数参数的值传递和引用传递

论javascript函数参数的值传递和引用传递        众所周知,在JavaScript里调用函数传参的方式分为值传递和引用传递两中方式,在这里我们来研究一下,值传递和引用传递的区别。        首先我们拿概念来说,在js函数传参时,如果传递的是数值类型的数据我们称之为“值传递”,如果传递的是对像类型的数据...

z1808232384的博客 366

深入理解JavaScript的值传递和引用传递

JavaScript有5种基本的数据类型,分别是:布尔、null、undefined、String和Number。这些基本类型在赋值的时候是通过值传递的方式。值得注意的是还有另外三种类型: Array、Function和Object,它们通过引用来传递。从底层技术上看,它们三都是对象。 基本数据类型 如果一个基本的数据类型绑定到某个变量,我们可以认为该变量包含这个基本数据类型的值。 ...

你如今的气质里,藏着你走过的路,经历过的事,读过的书,和爱过的人。 272

谈谈我对JavaScript值传递和引用传递的理解

数据类型 ECMAScript 标准定义了 7 种数据类型:

qq_43615908的博客 218

js中的值传递和引用传递

在js中值传递和引用传递是让人容易混淆的问题,下面我就来根据自己的理解来区分一下这两个传递方式: 值传递 值传递是两个变量传递前后互补干扰,无法造成影响,下面代码举例说明 var a=7; function fuc(a){ a++; } fuc(a) console.log(a); //7 向上面这样,当我们给a赋值之后,在通过调用函数调用吧a的值自增,但是改变的a的值只是在函数中...

lhxsirky的博客 920

JS的值传递和引用传递

JS中有5种基本数据类型,它们在赋值的时候是通过值传递,而引用数据类型(对象)是通过引用来传递. 举个例子: var x = 10; var y = 'abc'; var a = x; var b = y; a = 5; b = 'def'; console.log(x, y, a, b); // 10, 'abc', 5, 'def' 基本数据类型,改变a,b的值并没有影响x,y当我...

Hanhanyoona的博客 473

JS值传递和引用传递

方法的形式参数如果是一个基本数据类型,形式参数的改变对实际参数没有影响!(具体的数据值) 方法的形式参数如果是引用数据类型,形式参数的改变会直接影响实际参数!(地址和值) 值传递就是在函数调用中函数内部开辟了空间,结果函数没有改变到外部a的值,所有a的值还是10 var a = 10; console.log(a); //10 function fn(a){ a += 10; } ...

s1351295250的博客 247

JavaScript值传递和引用传递

值传递是只把对象的值传入函数,函数中可以使用这个值,但却无法更改该对象的值。 引用传递是将整个对象本身(或地址)传入函数,在函数中既可调用对象的值,也可改变对象的值。 复制变量 1. 基本类型 var num1 = 5; var num2 = num1; 2. 引用类型(对象) var obj1 = new Object(); var obj2 =

TianRangDeJieHuo的博客 380
上一篇: js参数转换,各种类型参数在另一种类型里代表什么
下一篇: 排序算法和分析史上最全
sells2012
博客等级 码龄15年 10粉丝 22原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值