Connecting Tech Pros Worldwide Forums | Help | Site Map

Gaining reference to an outer this?

Robert Mark Bram
Guest
 
Posts: n/a
#1: Jul 20 '05
Howdy All!

Can anyone help with using "this" here please?

function TestObject()
{
this.one = one;
this.two = two;
} // end TestObject constructor

function one()
{
// "this" would refer to a TestObject (~1~)

// Make a select control.. and assign it an onChange handler.
var dateSelect = document.createElement ("select");
dateSelect.onchange =
function hide()
{
// "this" refers to a Select object.

// How can I refer to the TestObject at (~1~) so I can
// call two() on that particular instance?
}; // end hide function
} // end function one

function two()
{
alert ("in function two");
} // end function two

Thanks for any help!

Rob
:)



Lasse Reichstein Nielsen
Guest
 
Posts: n/a
#2: Jul 20 '05

re: Gaining reference to an outer this?


"Robert Mark Bram" <relaxedrob@remove.this.optusnet.com.au> writes:
[color=blue]
> function one()
> {
> // "this" would refer to a TestObject (~1~)[/color]

Correct.
[color=blue]
> // Make a select control.. and assign it an onChange handler.
> var dateSelect = document.createElement ("select");[/color]

Add:
var thisTestObject = this;
to get a variable as reference to the testObject, instead of just
"this".
[color=blue]
> dateSelect.onchange =
> function hide()
> {
> // "this" refers to a Select object.[/color]

Correct.
[color=blue]
> // How can I refer to the TestObject at (~1~) so I can
> // call two() on that particular instance?[/color]

Use the variable "thisTestObject". The function expresion "hide"
creates a closure, so it remembers the value of the "thisTestObject"
variable.

/L
--
Lasse Reichstein Nielsen - lrn@hotpop.com
Art D'HTML: <URL:http://www.infimum.dk/HTML/randomArtSplit.html>
'Faith without judgement merely degrades the spirit divine.'
Robert Mark Bram
Guest
 
Posts: n/a
#3: Jul 20 '05

re: Gaining reference to an outer this?


Thank you Lasse!
[color=blue]
> Add:
> var thisTestObject = this;
> to get a variable as reference to the testObject, instead of just
> "this".[/color]

It works perfectly. :)

Rob
:)


Closed Thread