VR2
07-07-2006, 10:07 AM
My problem is with passing a method of an object and losing the "context" parent object...(you can see why I struggle on google with this...)
This is what I mean..
<HTML>
<BODY>
<SCRIPT>
// Object Definition
function Person(sName)
{
// Properties
this.Name = sName;
// Methods
this.SayHello = function()
{
alert("Hello, my name is " + this.Name);
};
}
// Create instance of person
var player = new Person("Kevin");
player.SayHello(); // Works OK
// Function to run a function....
function PassCallback(ptrFunc)
{
// Just run the passed function
ptrFunc();
}
// This will display "Hello, my name is undefined"
PassCallback(player.SayHello);
</SCRIPT>
</BODY>
</HTML>
So it seems that by passing the function pointer all instance variables that were available to the "SayHello" method (this.Name for example) have gone up in smoke.
Up until now I've overcome this by simulating "Interfaces", like this
// Function to run a function....
function PassObjInterface(obj)
{
// The object we passed HAD BETTER support the SayHello() method, else we're in trouble!
if (!obj.SayHello)
{
alert("Object passed does not support an Interface that includes a SayHello method");
return;
}
obj.SayHello();
}
But I'd really like to know how to pass a function pointer to another method or function, to be used as a callback, WITHOUT losing the object instance data when the callback function is executed.
Any takers?
This is what I mean..
<HTML>
<BODY>
<SCRIPT>
// Object Definition
function Person(sName)
{
// Properties
this.Name = sName;
// Methods
this.SayHello = function()
{
alert("Hello, my name is " + this.Name);
};
}
// Create instance of person
var player = new Person("Kevin");
player.SayHello(); // Works OK
// Function to run a function....
function PassCallback(ptrFunc)
{
// Just run the passed function
ptrFunc();
}
// This will display "Hello, my name is undefined"
PassCallback(player.SayHello);
</SCRIPT>
</BODY>
</HTML>
So it seems that by passing the function pointer all instance variables that were available to the "SayHello" method (this.Name for example) have gone up in smoke.
Up until now I've overcome this by simulating "Interfaces", like this
// Function to run a function....
function PassObjInterface(obj)
{
// The object we passed HAD BETTER support the SayHello() method, else we're in trouble!
if (!obj.SayHello)
{
alert("Object passed does not support an Interface that includes a SayHello method");
return;
}
obj.SayHello();
}
But I'd really like to know how to pass a function pointer to another method or function, to be used as a callback, WITHOUT losing the object instance data when the callback function is executed.
Any takers?