Javascript passing object to function

2019-03-29 05:58发布

问题:

Quick question on Javascript to which I can't find a clear concise answer.

I'm building an app that's way ahead of anything I've done before and involves multiple classes being instantiated. These objects are then passed into a processing class that checks user inputs, draws onto canvas and updates the objects that it has been passed.

I am wondering, how does JavaScript handle passing objects to functions? Am I passing a copy of the object, or am I passing a reference to the object?

So if my controller class alters one of the objects variables, is that changed everywhere or just in the object that that controller sees?

Sorry for such a simple, possibly easily testable question but I'm not even sure if I'm making a class correctly at this point thanks to errors piling up.

回答1:

When passing in a primitive type variable like a string or a number, the value is passed in by value. This means that any changes to that variable while in the function are completely separate from anything 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 in an object, however, passes it in by reference. In this case, any property of that object is accessible within 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:

As well described in https://stackoverflow.com/a/5314911/636348, in JavaScript it's always pass by value, but for objects the value of the variable is a reference.

So, it's not a pure pass by reference. Here's an example to understand this concept:

E.g.:

x = {member:"foo"}

If you change the object with another object inside a function, you won't get the new object outside the function scope because you just create another object. The original reference is still bound to the original object:

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

changeObject(x);
alert(x.member)

output: foo

instead, if you alter a member inside a function, the object will be changed:

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

changeMember(x);
alert(x.member)

output: bar



回答3:

If you pass in a variable which is pointing to an object, it passes a reference to the object. If you pass in an object literal, then obviously no other class or function will be able to change that object.