JavaScript Pass-by Reference vs. Pass-by Value
JavaScript employs both pass-by-value and pass-by-reference mechanisms. Primitives, such as numbers and strings, are passed by value, meaning a copy of the primitive is created in the called function. In contrast, non-primitives, primarily objects, are passed by reference.
In the case of objects, a reference to the object is passed rather than a copy. This means that modifying the reference variable in the called function will not affect the reference in the caller, as demonstrated in the example provided:
var a = { key: 'value' }; replace(a); // a still holds its original value update(a); // a's contents change
Confusion with the rectangle Function
The example in the question includes a nested function rectangle with the my parameter. This parameter is initially undefined, but is defined within the function. The reason for this setup is to provide a way to share data between the rectangle function and its inner area function.
While the my parameter is not initially defined in the rectangle function, it is an object reference passed by reference. As such, when it is assigned within the rectangle function, it creates a new reference to an object that can be modified both within the rectangle and area functions, even though the area function does not directly receive the my parameter.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3