1
votes

From what I know, javascript, that is also based on ECMAscript the same as actionscript, does not really pass objects by reference. At least that's what I've read lately. For instance:

function doStuff(myObj){
   myObj.name = 'groovy chicken';
   myObj = null;
}
var newObj = new Object();
doStuff(newObj);

This is an example I found in a book 'Professional Javascript for web developers'. Although you are passing an object to the function, and adding the name property actually adds the property to your initial object, when you set to null, the object is destroyed in the local scope not in the global scope.

To me, this is still a bit confusing, since the myObj you have, is still pointing the same place as newObj and you can actully add or alter properties. The only difference is that you can not destroy it from the global scope.

So I'm wondering if the same also applies to actionscript, since from what I've read, actionscript 3 does actually pass objects by reference and I've not read anything stating the opposite.

2

2 Answers

2
votes

Very few modern programming languages pass by reference (at least by default). In the twisted terminology of "pass by..", you're passing a reference by value. Here's how to think about it:

  • myObj and newObj are just variables, names for things.
  • The value of those variables are references to the object
  • When you call doStuff(), you're binding the name myObj to a new reference to your object (i.e. the reference itself was passed by value)
  • The reference points to a chunk of memory with some stuff in it, which is what lets you change the name inside of doStuff()
  • You can see that change by inspecting either variable because both variables contain references to the same object
  • myObj = null reassigns the variable to nothing, and in the process, it "destroys" the reference, but it doesn't destroy the object.
  • When the garbage collector notices there are no more references to an object, it will destroy that object
0
votes

I'll try to help you understand the working of JavaScript's object:

when you say,

var newobj = new Object();

Here, newobj is only a name to the memory location allocated when you created an instance of Object.

When you pass newobj, it takes along the reference to the memory location. Now, myObj in the function is another name to the same memory location.

Adding a method 'name' adds it to the memory location and hence is available to both newobj and myobj.

when you set myobj to null, it removes that named reference and newobj still remains alive with the name property set.

But, I dont have an idea on how this works in actionscript.