我通过以下示例获得了 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/