This is a very very basic question but for some reason I'm struggling and cannot find a good reference to it.
Say I have this JScript
code running under WSH
:
function func(myStr) {
var res = "abc";
myStr = res;
}
function main() {
var myStr = new String();
WScript.Echo(myStr);
func(myStr);
WScript.Echo(myStr);
}
main();
I passing String
object to func
and expect func
to set the value of object. However, func
uses operator =
which does copy the content but generate a new reference
I reviewed this post, How do I correctly clone a JavaScript object?, and couldn't find what I was looking for.
Do we have a simple, straightforward solution to this?
The main thing is: objects are passed by reference. Other things, like strings, arrays, numbers,... are passed by value.
Every time you pass a string to a function, only a copy of its value gets passed to that function (So don't consider your string object to be an object, don't ask about cloning.). But any link to the original variable is lost.
Objects, on the other hand, when you pass them to a function, the address (pointer / reference) of the object is passed to the function, so it's the same variable inside as outside. So anything that happens to that object inside the function will affect the object on the outside (as well).
Now, look at a similar code, but with passing objects
var myObject = {};
myObject.txt = 'Foo';
console.log(myObject.txt);
func(myObject);
console.log(myObject.txt);
function func(obj) {
obj.txt = 'Hello World';
}