nu*****@naver.com wrote:
========= test.js ===================
function Test()
{
this.temp = "hehehehe" ;
this.method1 = method1 ;
}
function method1()
{
alert(this.temp) ;
}
========= test.html =====================
<BODY>
<a id="test">aaaaaaaa</a>
<script>
var obj = new Test(window) ;
document.all['test'].attachEvent("onclick",obj.testMethod) ;
</script>
</BODY>
Result :
This Alert "undefined" !!!
What?
Can't I attach my Own Object Method to Target ?
Please post the answer!!
Short answer:
Saying:
a = b;
c = b;
is the same as saying:
c = a;
Except for the wasted effort.
If I say:
x = new Object();
x.method = someFunc;
Then I say:
document.getElemetById( 'test' ).attachEvent(
'onclick', x.method );
It is roughly the same as saying:
document.getElementById( 'test' ).attachEvent(
'onclick', someFunc );
The rest of this post is superfluous, just in case you need a long
explanation of the above:
You declare a function:
function method1( ) {
You tell it to popup a message displaying the value of a variable. In
particular, the value of the .temp member of whatever object may
constitute 'this'.
You then create an object.
var obj = new Test( window );
First: the reference to 'window' here is superfluous. If you're not
using it, get rid of it.
More importantly, what this does is instantiate a new Object object and
calls the constructor function Test().
Test does this:
It assigns a String value to the 'temp' member of the new Object
object.
It assigns a reference to the method1 function to the 'method1' member
of the new Object object.
So if you call it in this way:
obj.method1()
Then 'this' refers to 'obj'.
Your code above says:
document.all['test'].attachEvent("onclick",obj.testMethod) ;
I assume you meant:
document.all['test'].attachEvent("onclick",obj.method1);
Because you never defined any 'testMethod' anywhere in the entire
document.
What this revised version does is assigns a reference to the the
method1 function to be the onclick event handler of the 'test' element.
This is the same as assigning it as a method of the HTMLElement object
in question.
Same thing as you did when you assigned it to the new Test object,
isn't it?
So when onclick gets called, what will happen?
It is called as:
document.all['test'].onclick();
So 'this' will refer to the HTML element called 'test'.
Probably not a very good explanation. I'm tired. You'll get better
answers within the next few hours I'm sure.