In JavaScript, all variables are passed by value, which means that a copy of the original value is made and passed to the function. However, when the value is an object, such as an array or an object literal, the copy is a reference to the original object.
function f(a, b, c) { a = 3; // Reassignment changes the local variable only. b.push("foo"); // Property change affects the original object. c.first = false; // Property change affects the original object. } const x = 4; let y = ["eeny", "miny", "mo"]; let z = { first: true }; f(x, y, z); console.log(x, y, z.first); // Output: 4, ["eeny", "miny", "mo", "foo"], false
In the example above, the changes to the b and c objects are reflected in the original objects, while the reassignment of a has no effect.
In-depth Examples:
function f() { const a = ["1", "2", { foo: "bar" }]; const b = a[1]; // Copy the reference to the original array element a[1] = "4"; // Change the value in the original array console.log(b); // Output: "2" (Original value of the copied reference) }
In the first example, even though a has been modified, b still holds the original value because it is a copy of the reference.
function f() { const a = [{ yellow: "blue" }, { red: "cyan" }, { green: "magenta" }]; const b = a[1]; // Copy the reference to the original object a[1].red = "tan"; // Change the property in the original object console.log(b.red); // Output: "tan" (Property change is reflected in both variables) b.red = "black"; // Change the property through the reference console.log(a[1].red); // Output: "black" (Property change is reflected in both variables) }
In the second example, the change to a[1].red affects both a and b because they share the same object reference.
To create a fully independent copy of an object, you can use the JSON.parse() and JSON.stringify() methods to deserialize and serialize the object respectively. For example:
const originalObject = { foo: "bar" }; const independentCopy = JSON.parse(JSON.stringify(originalObject));
The above is the detailed content of How Does JavaScript Handle Pass-by-Value and Pass-by-Reference with Primitive Types and Objects?. For more information, please follow other related articles on the PHP Chinese website!