Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations derfloh on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Class Variables

Status
Not open for further replies.

kaoskorruption

Programmer
Joined
Jul 20, 2006
Messages
1
Location
US
I need a variable from within a class to be accessable from outside the class AND within other functions that are inside the class.

function test ( ) {
this.name = name;
this.div = createElement ( "div" );
body.appendChild ( this.div );
function name ( ) {
alert ( this.div.style.left );
}
}

var test = new test ( );
test.name ( );

When I try to do this, I get there error: this.div in function "name" has no properties. Using firefox. Whats the problem?
 
[1] First your naming is no good. Your instance should not be called the same as the class's name. (Put more imagination on naming, would you? here and inside the function. You use always same name to give yourself unnecessary confusion.)
>var test = new test ( );
>test.name ( );
[2] createElement(), appendChild()... you spare the parent document reference. Does it work at all?!
[3] Inline style properties have to be assigned else it is undefined.
[4] If you want to capture the property name at all, you have to return the value. The statement :
>this.name=name;
assign a pointer to the function "name" to the property "name" (so unnecessary source of confusion!). Hence without returning nothing, looking from outside, you won't see anything---that's natural.
[4'] Similarly, you statement :
>test.name;
is what? First it is just pointing to the function name(); you also not capturing anything from the statement and it just evaporates into void.

This may get it work as a start.
[tt]
function test ( ) {
this.name = name;
this.div = document.createElement ( "div" );
this.div.style.left="200px";
document.body.appendChild ( this.div );
function name ( ) {
//alert ( this.div.style.left );
return this.div.style.left;
}
}

window.onload=function() {
var xtest = new test ( );
var y=xtest.name();
alert(y);
}
[/tt]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top