473,473 Members | 1,879 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

'this' and prototypes

I have some code that's structured a bit like this:

Con = function(choice, el) {
this.choice = choice;
document.getElementById(el).onclick = this.choiceClicked;
}

Con.prototype.choiceClicked = function() {
alert(this.choice);
}

foo = new Con(1,"bar")

Why is it when I click on the element "bar" this choice alerts as
'undefined'? In the prototype 'this' is the element clicked and not what
is was expecting (the object 'foo'). I'd like the 'this' in the
prototype to refer to 'foo': is there some way to do this?

Andrew Poulos
Sep 15 '05 #1
7 1265
To understand what is happening read:

http://www.brockman.se/writing/metho...nces.html.utf8

The simplest way I've found to fix it is to use the prototype.js
library:

http://prototype.conio.net/

If you do this:

document.getElementById(el).onclick =
this.choiceClicked.bindAsEventListener(this);

'this' will be what you expect.

Hope this helps,
Cathy

Sep 15 '05 #2
EventListener <Ev***********@gmail.com> wrote:
Someone else wrote (context restored)
Con = function(choice, el) {
this.choice = choice;
document.getElementById(el).onclick = this.choiceClicked;
}


I'm extremely curious as to why this doesn't work as one would intend.
Clearly "this" in the first line refers to the Con object; it
therefore seems that it should have been possible for the ECMA script
designers to differentiate

document.getElementById(el).onclick = this.choiceClicked;

from

document.getElementById(el).onclick = 'this.choiceClicked()';

Is the basic issue that event attributes may only be references to
global functions? Would

var a={};
a.foo=function() {alert('foo');}

document.getElementById( 'bar' ).onclick=a.foo;

work as intended?

--
Christopher Benson-Manica | I *should* know what I'm talking about - if I
ataru(at)cyberspace.org | don't, I need to know. Flames welcome.
Sep 15 '05 #3


Christopher Benson-Manica wrote:

it
therefore seems that it should have been possible for the ECMA script
designers to differentiate

document.getElementById(el).onclick = this.choiceClicked;

from

document.getElementById(el).onclick = 'this.choiceClicked()';


There is certainly a difference between the result of the right hand
side expression in the first assigment and the one in the second assigment.
The first yields a function object, the second a string.
And the function object the first right hand side expression yields is
not bound to the this object, it is simply a function object. The this
object only exists when a function is called.

That is what the ECMAScript specification deals with. Event handlers and
HTML element attributes are not in any way part of that specification or
what its designers dealt with.

--

Martin Honnen
http://JavaScript.FAQTs.com/
Sep 15 '05 #4
Martin Honnen <ma*******@yahoo.de> wrote:
There is certainly a difference between the result of the right hand
side expression in the first assigment and the one in the second assigment.
The first yields a function object, the second a string.


Well darn it. I was and am aware of the fact that 'this' refers to
the element that generated the event in an event handler, so I really
can't explain how I managed to produce that post. Time to make some
more coffee.

--
Christopher Benson-Manica | I *should* know what I'm talking about - if I
ataru(at)cyberspace.org | don't, I need to know. Flames welcome.
Sep 15 '05 #5
On 15/09/2005 14:38, Andrew Poulos wrote:

[snip]
Con = function(choice, el) {
this.choice = choice;
document.getElementById(el).onclick = this.choiceClicked;
}

Con.prototype.choiceClicked = function() {
alert(this.choice);
}


[snip]

This issue has been discussed many, many times in the past. The most
recent I recall is

Subject: .addEventListener() not finding the right object method
Date: 2005/08/26 14:37 GMT
Message ID: 11**********************@g44g2000cwa.googlegroups. com
<URL:http://groups.google.co.uk/group/comp.lang.javascript/browse_thread/thread/e8702c77bcd68fc8/45eed8c571173a3e>

where I referenced

Subject: How to understand the javascript class model?
Date: 2005/08/25 02:28 GMT
Message ID: de***********@mail.cn99.com
<URL:http://groups.google.co.uk/group/comp.lang.javascript/browse_thread/thread/9b041b9103b6de0f/2065870c97d74b50>

from the day before.

Mike

--
Michael Winter
Prefix subject with [News] before replying by e-mail.
Sep 15 '05 #6
Andrew Poulos wrote:
I have some code that's structured a bit like this:

Con = function(choice, el) {
this.choice = choice;
document.getElementById(el).onclick = this.choiceClicked;
}

Con.prototype.choiceClicked = function() {
alert(this.choice);
}

foo = new Con(1,"bar")

Why is it when I click on the element "bar" this choice alerts as
'undefined'? In the prototype 'this' is the element clicked and not what
is was expecting (the object 'foo'). I'd like the 'this' in the
prototype to refer to 'foo': is there some way to do this?


I learned to use closures to do this.

function Con(choice, e1)
{
this.choice = choice;
document.getElementById(e1).onclick = Con.createClickHandler(this)
}

function _Con_createClickHandler(obj)
{
return function(event)
{
obj.choiceClicked();
}
}

function _Con_choiceClicked()
{
alert(this.choice);
}

Con.prototype.choiceClicked = _Con_choiceClicked;
Con.createClickHandler = _Con_createClickHandler;

Sep 16 '05 #7
On 16/09/2005 11:27, Robert wrote:

[snip]
function Con(choice, e1)
{
this.choice = choice;
document.getElementById(e1).onclick = Con.createClickHandler(this)
}

function _Con_createClickHandler(obj)
{
return function(event)
{
obj.choiceClicked();
}
}
Incidentally, this will still create the memory leak that you've harped
on about recently. :P

In the factory function, there is an object reference to a DOM object,
obj. This object will (eventually) have a property that is a reference
to a function object. This function object has, in its scope chain, a
reference to the original DOM object.

This is exactly the same process that you've seen elsewhere. The only
difference is that the assignment is deferred to another execution context.

The discussions I linked to mention workable alternatives, as will
previous threads in this group.
function _Con_choiceClicked()
{
alert(this.choice);
}

Con.prototype.choiceClicked = _Con_choiceClicked;
Con.createClickHandler = _Con_createClickHandler;


Don't create unnecessary intermediary globals. Instead, assign the
function object to the property directly:

Con.prototype.choiceClicked = function() {
alert(this.choice);
};

Mike

--
Michael Winter
Prefix subject with [News] before replying by e-mail.
Sep 22 '05 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

145
by: David MacQuigg | last post by:
Playing with Prothon today, I am fascinated by the idea of eliminating classes in Python. I'm trying to figure out what fundamental benefit there is to having classes. Is all this complexity...
14
by: fb | last post by:
Does the C language require you to prototype functions? If it's not required, is it recommended?
26
by: William L. Bahn | last post by:
Am I invoking any undefined behavior in the following program? /* Function to print out the bit pattern stored in a variable regardless of type */ #include <limits.h> /* CHAR_BIT */ #include...
9
by: Grumble | last post by:
Hello everyone, I've come across some strange code. Here it is, stripped down: int main(void) { int *foo; int *bar(); foo = bar(0); return 0;
13
by: DevarajA | last post by:
If a function is visible everywhere, even out the file where it is declared and defined, why should i write prototypes? -- Devaraja (Xdevaraja87^gmail^c0mX) Linux Registerd User #338167...
19
by: elzacho | last post by:
It is my understanding that prototypes in C are purely optional. To my experience, until today I guess, this has been the case (other than eliminating compiler warning messages). However, today...
7
by: junky_fellow | last post by:
Can a function have two different prototypes ? If not , then how can main() have two different prototypes ? int main(void) and int main argc(int argc, char *argv) I mean to say, if I declare...
20
by: Ari Krupnik | last post by:
scripts can add methods to the prototypes of builtin objects in JaavScript. I can assign functions to String.prototype.*, for instance. I want to add a method to Node, but when I try to execute...
73
by: Steph Barklay | last post by:
Hi, I'm currently taking a data structures course in C, and my teacher said that function prototypes are not allowed in any of our code. He also said that no professional programmers use function...
31
by: Tommy | last post by:
struct stat *stats IF_LINT (= 0); I don't know why "IF_LINT (= 0)" is needed ? Source is df.c of df program on Linux coreutils-5.2.1\coreutils-5.2.1\src Thanks!
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
1
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
1
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
muto222
php
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.