References classes?
what's the correct way to reference a class, in this case from the same package. the code below shows class "Two" attempting to trace the value of a variable in class "One". no success. trace returns undefined.
//Class One
package
开发者_开发技巧{
import flash.display.Sprite;
public class One extends Sprite
{
public var myString:String = "My String";
public function One()
{
new Two();
}
}
}
//Class TWO
package
{
public class Two
{
private var oneClass:Class = One; // <- is that right?
public function Two()
{
trace(oneClass.myString);
}
}
}
There is an error in trace(oneClass.myString);
because myString
isn't static. But besides that, you can assign One
to oneClass
A reference of type Class
doesn't have any property of the class or the object, is not an instance is just a reference to the constructor of that class. i.e:
public class One {
static public var classValue = "Hello";
public var instanceValue = "World!";
}
public class Two {
public function Two() {
trace( One.classValue ); // this traces: Hello
trace( One.instanceValue ); // this throws an Error
var classReference:Class = One;
trace( classReference.classValue ); // this throws an Error
trace( classReference.instanceValue ); // this throws an Error
var objectReference:One = new classReference();
trace( objectReference.classValue ); // this throws an Error
trace( objectReference.instanceValue); // this traces: World!
}
}
The class properties (static ones) only can be acceded from the Class directly (like One.classValue
) not from a Class
reference and instance properties (NOT static ones) can only be acceded from objects of that class (like new One().instanceValue
)
myString in class One is not static. So it doesn't belong to the class, but to the instances. That's why your code doesn't work. Try with :
static public var myString:String = "My String";
精彩评论