PDA

View Full Version : difference between variable/objects


jglazener
10-17-2002, 10:43 PM
im just learning actionscript and am totally new to OO prog.

im confused about the more subtle diff. b/w variables and objects and would really be appreciative of anyone's help. thank you.

it seems like at times i can put in a variable any time i want. cant i then, using dot syntax make another variable inside that variable? why would i want to creat an abject?

here is an example of what i dont understand, what is the difference between these scenarios, or is scenario B even possible. this may be a bad example so if it is ill take a more general answer.

//scenario A

suitcase= new Object();
suitcase.billfold=1;
billfold=new Object();
billfold.dollars=0; //darn


//scenario B
_root.suitcase = 1;
_root.suitcase.billfold=1; //can i do this?
_root.suitcase.billfold.bills=0;

pom
10-17-2002, 11:03 PM
Well, try it... As pixelWit says, experience and experiment are... well I can't remember what he said but you get the picture. If you trace (_root.suitcase.billfold);you get nada, undefined.

Basically the advantage of objects is that you can pack lots of things in a single location.

pom :cool:

jglazener
10-17-2002, 11:07 PM
ok, thanks for the response.

..but (there is always a but) when i define a variable is it an object? can that variable have its own proerties or variables without defining it as an object?

pom
10-17-2002, 11:08 PM
A variable is a variable, not an object. Objects contain variables, as a matter of fact. Variables contain a value. They are 2 different things, really.

Cheers.

pom :cool:

pom
10-17-2002, 11:10 PM
Actually, to create an object, you have to call the constructor (which is not the case for a variable)myObj=new Object();
// OR
myObj={};

LuxFX
10-21-2002, 08:20 PM
objects can contain other variable or even methods, and can reference themselves and their encapsulated variables and methods with the this keyword. if you want to use object-oriented style code, here's an example:

function bo_GetWidth()
{
return this.x2 - this.x1;
}

function bo_GetHeight()
{
return this.y2 - this.y1;
}

function bo_GetArea()
{
return this.GetWidth() * this.GetHeight();
}

function boxObject(x1, y1, x2, y2)
{
this.x1 = x1;
this.y1 = y1;
this.x2 = x2;
this.y2 = y2;
}

boxObject.prototype.GetWidth = bo_GetWidth;
boxObject.prototype.GetHeight = bo_GetHeight;
boxObject.prototype.GetArea = bo_GetArea;

var myBox = new boxObject(0, 0, 10, 30);
trace(myBox.GetWidth()); // returns: 10
trace(myBox.GetHeight()); // returns: 30
trace(myBox.GetArea()); // returns: 300

As you can see, all of the contained variables are referenced internally by the this keyword. I can create method functions externally and then link them to the 'prototype' of the object (think of it as accessing the structure of the object) afterwards.

Hope this helps!
LuxFX