开发者

ActionScript 3: Unexpected behaviour of array, when pushing an element

开发者 https://www.devze.com 2023-02-01 01:09 出处:网络
I am a bit confused by one expression: var nodes:Array = new Array(); for (var i:int = 0; i<=3; i++)

I am a bit confused by one expression:

var nodes:Array = new Array();
for (var i:int = 0; i<=3; i++)
{
   var node:Node = new Node(i)
   nodes.push(node);
}
trace(nodes[0].id + ":" + nodes[1].id);

Returned me 0:0 instead of 0:1 as I expected.

public class Node
{
   public var id:int;
   public function Node(id:int)
   {
      id = id
   }
}

How this c开发者_StackOverflow社区an be explained?


You are setting the argument called id equal to itself, which is clearly not the intended behavior.

When there are instance variables that have the same names as arguments, you need to be explicit about which variable you wish to set:

public function Node(id:int) {
   this.id = id;
}

This would work too:

public function Node(an_id:int) {
   id = an_id; //here it implicitly assigns the instance variable
}


Simple, but very very hard to spot when you are in the middle of it: The constructor in your node class needs to look like this instead:

public function Node(id:int)
{
    this.id = id
}

When you omit the "this" the temporary variable id gets assigned to itself, hence the '0' in the output.


My first guess:

this.id = id instead of id = id

You need to call your object var implicitly

0

精彩评论

暂无评论...
验证码 换一张
取 消