Passing variables by reference allows functions to modify the original variables in the calling context. While JavaScript doesn't have true pass-by-reference, it does provide ways to achieve similar functionality.
To modify objects' contents, pass them by value to functions. JavaScript allows modifying object properties, as seen in the example below:
function alterObject(obj) { obj.foo = "goodbye"; } var myObj = { foo: "hello world" }; alterObject(myObj); alert(myObj.foo); // "goodbye"
Iterate through array properties with numeric indexes to modify individual cells:
var arr = [1, 2, 3]; for (var i = 0; i < arr.length; i++) { arr[i] = arr[i] + 1; }
Note that true pass-by-reference (modifying simple variables in the calling context) is not possible in JavaScript. The following example illustrates this concept:
function swap(a, b) { var tmp = a; a = b; b = tmp; } var x = 1, y = 2; swap(x, y); alert("x is " + x + ", y is " + y); // "x is 1, y is 2"
Unlike C , JavaScript does not support true pass-by-reference, where functions could modify simple variables in the calling context. Instead, JavaScript only allows passing references to modifiable objects, which modifies their contents but not their references.
The above is the detailed content of How Can I Simulate Pass-by-Reference in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!