Object that passes Javascript to work

A quick Javascript question that I cannot find a clear short answer to.

I am creating an application that is ahead of everything that I did before, and includes several instances that are created. These objects are then passed to the processing class, which checks the user input, draws on the canvas and updates the objects that it was transferred.

I am wondering how JavaScript handles passing objects in functions? Am I passing an instance of an object or passing a reference to an object?

So, if my controller class changes one of the variables of the object, does it change everywhere or only in the object that this controller sees?

Sorry for such a simple, perhaps easily verifiable question, but I'm not even sure if I am doing the class right at this point due to a heap of errors.

+6
source share
3 answers

When passed in a primitive type variable, like a string or a number, the value is passed in by value . This means that any changes to this variable in the function are completely separate from everything that happens outside the function.

function myfunction(x) { // x is equal to 4 x = 5; // x is now equal to 5 } var x = 4; alert(x); // x is equal to 4 myfunction(x); alert(x); // x is still equal to 4 

Passing to an object, however, passes it in by reference . In this case, any property of this object is available inside the function.

 function myobject() { this.value = 5; } var o = new myobject(); alert(o.value); // o.value = 5 function objectchanger(fnc) { fnc.value = 6; } objectchanger(o); alert(o.value); // o.value is now equal to 6 
+2
source

As described in fooobar.com/questions/702 / ... , in JavaScript it always passes by value, but for objects, the value of the variable is a reference.

So this is not a clean pass by reference. Here is an example to understand this concept:

eg:.

 x = {member:"foo"} 

If you change the object to another object inside the function, you will not get a new object outside the scope because you simply create another object. The source link is still bound to the source object:

 function changeObject(x) { x = {member:"bar"}; } changeObject(x); alert(x.member) 

output: foo

instead, if you change an element inside a function, the object will be changed:

 function changeMember(x) { x.member = "bar"; } changeMember(x); alert(x.member) 

conclusion: bar

+3
source

If you pass a variable that points to an object, it passes a reference to the object. If you pass an object literal, then obviously no other class or function can change this object.

+1
source

Source: https://habr.com/ru/post/948302/


All Articles