javascript - javascript 中的原始数据类型和引用数据类型

标签 javascript

我通过以下示例获得了 javascript 中的按引用传递和原始数据类型。

//This is pass by value example

var firstPerson = "Manish";  
var secondPerson = firstPerson;

firstPerson = "Vikash"; // value of firstPerson changed

console.log(secondPerson); // Manish
console.log(firstPerson); // Vikash



//This is the same as above example

var firstPerson = {name: "Manish"};
var secondPerson = firstPerson;

firstPerson.name = "Vikash";

console.log(secondPerson.name); // Vikash
console.log(firstPerson.name); // Vikash

在第一个示例中,我知道我正在将 firstPerson 变量的值复制到 secondPerson 中,以便它保存该值并打印它。它不关心将任何值重新分配给 firstPerson 变量。

但是第二个例子呢?

为什么它通过执行 secondPerson.name 打印 vikash,即使我已经复制了 firstPerson = {name: "Manish"}进入第二人称?

最佳答案

我总是这样解释的:

// 'firstPerson' holds a reference to a string "Manish".
var firstPerson = "Manish";  
// Now you state that 'secondPerson' should hold the reference
// to the same string - "Manish". Since it's a string (a primitive)
// it will be "copied" (depends on implementation), see comments.
var secondPerson = firstPerson;

// Now you say that 'firstPerson' should hold a reference to another
// string, "Vikash".
// That didn't change what the 'secondPerson' refers to, though!
firstPerson = "Vikash";

console.log(secondPerson); // Manish
console.log(firstPerson); // Vikash


// 'firstPerson' holds a reference to an object.
// **Inside** this object, 'name' holds a reference
// to a string "Manish".
var firstPerson = {name: "Manish"};
// 'secondPerson' holds a reference to the same object.
var secondPerson = firstPerson;
// Now you say that the 'name' inside this object should refer
// to another string, "Vikash".
// **That didn't change** what 'firstPerson'
// or 'secondPerson' refers to, though.
firstPerson.name = "Vikash";

console.log(secondPerson.name); // Vikash
console.log(firstPerson.name); // Vikash

您可以在这张图中表示:

// First example
firstPerson    -----> "Manish"
                   |
secondPerson   ----|

// First example after the re-assigment:
firstPerson    -----> "Manish"

secondPerson   -----> "Vikash"

// Second example
firstPerson    -----> { name:    -----> "Manish" }
                   |
secondPerson   ----|

// Second example after re-assignment:
firstPerson    -----> { name:    -----> "Vikash" }
                   |
secondPerson   ----|   <--- this arrow didn't change!

注意箭头在重新分配后如何变化。

关于javascript - javascript 中的原始数据类型和引用数据类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35029887/

相关文章:

javascript - 在 html 中单击 href

javascript - 使用单个代码分割文本

php - LinkedIn Api 登录按钮未显示

嵌套 CSS 类的 Javascript 正则表达式

javascript - 简单的 javascript 更正(日期/时间)

javascript - 使用网络蓝牙从 BLE 设备读取数据?

javascript - 使用 CryptoJS 在 Javascript 中加密并在 Java 中解密

javascript - 如何解决与 react-native-device-info 相关的 React Native Firebase 错误 (messaging().getToken())

javascript - 从 json 字符串解析图像

javascript - 当有人使用 javascript 或 jquery 粘贴文本时,如何仅禁用/删除输入字段内文本开头的空格?