Gaining reference to an outer this?

R

Robert Mark Bram

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
:)
 
L

Lasse Reichstein Nielsen

Robert Mark Bram said:
function one()
{
// "this" would refer to a TestObject (~1~)
Correct.

// Make a select control.. and assign it an onChange handler.
var dateSelect = document.createElement ("select");

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

// How can I refer to the TestObject at (~1~) so I can
// call two() on that particular instance?

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

/L
 
R

Robert Mark Bram

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

It works perfectly. :)

Rob
:)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top