473,721 Members | 2,036 Online
Bytes | Software Development & Data Engineering Community
+ 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.getEle mentById(el).on click = this.choiceClic ked;
}

Con.prototype.c hoiceClicked = function() {
alert(this.choi ce);
}

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 1278
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.getEle mentById(el).on click =
this.choiceClic ked.bindAsEvent Listener(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.getEle mentById(el).on click = this.choiceClic ked;
}


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.getEle mentById(el).on click = this.choiceClic ked;

from

document.getEle mentById(el).on click = 'this.choiceCli cked()';

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

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

document.getEle mentById( 'bar' ).onclick=a.foo ;

work as intended?

--
Christopher Benson-Manica | I *should* know what I'm talking about - if I
ataru(at)cybers pace.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.getEle mentById(el).on click = this.choiceClic ked;

from

document.getEle mentById(el).on click = 'this.choiceCli cked()';


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*******@yaho o.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)cybers pace.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.getEle mentById(el).on click = this.choiceClic ked;
}

Con.prototype.c hoiceClicked = function() {
alert(this.choi ce);
}


[snip]

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

Subject: .addEventListen er() not finding the right object method
Date: 2005/08/26 14:37 GMT
Message ID: 11************* *********@g44g2 00...legr oups.com
<URL:http://groups.google.c o.uk/group/comp.lang.javas cript/browse_thread/thread/e8702c77bcd68fc 8/45eed8c571173a3 e>

where I referenced

Subject: How to understand the javascript class model?
Date: 2005/08/25 02:28 GMT
Message ID: de***********@m ail.cn99.com
<URL:http://groups.google.c o.uk/group/comp.lang.javas cript/browse_thread/thread/9b041b9103b6de0 f/2065870c97d74b5 0>

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.getEle mentById(el).on click = this.choiceClic ked;
}

Con.prototype.c hoiceClicked = function() {
alert(this.choi ce);
}

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.getEle mentById(e1).on click = Con.createClick Handler(this)
}

function _Con_createClic kHandler(obj)
{
return function(event)
{
obj.choiceClick ed();
}
}

function _Con_choiceClic ked()
{
alert(this.choi ce);
}

Con.prototype.c hoiceClicked = _Con_choiceClic ked;
Con.createClick Handler = _Con_createClic kHandler;

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

[snip]
function Con(choice, e1)
{
this.choice = choice;
document.getEle mentById(e1).on click = Con.createClick Handler(this)
}

function _Con_createClic kHandler(obj)
{
return function(event)
{
obj.choiceClick ed();
}
}
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_choiceClic ked()
{
alert(this.choi ce);
}

Con.prototype.c hoiceClicked = _Con_choiceClic ked;
Con.createClick Handler = _Con_createClic kHandler;


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

Con.prototype.c hoiceClicked = function() {
alert(this.choi ce);
};

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
6316
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 unecessary? Here is an example of a Python class with all three types of methods (instance, static, and class methods). # Example from Ch.23, p.381-2 of Learning Python, 2nd ed. class Multi:
14
2732
by: fb | last post by:
Does the C language require you to prototype functions? If it's not required, is it recommended?
26
1985
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 <stdio.h> /* putc() */ void printbits(unsigned char *p, int bytes);
9
1913
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
1467
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 http://counter.li.org
19
3147
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 I wrote a routine to search an array for values greater than a certain limiting value (double) and something weird happened. When debuging I noticed that I passed the limiting value to the routine yet inside the function this value was garbage. ...
7
2378
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 main in either of the above mentioned ways my compiler does not give any warning. How can it accept two different prototypes ?
20
2123
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 the following IE says "'Node' is undefined." Mozilla works as I expected it to. Is Node called something else in IE? Does IE not allow manipulating the prototypes of some builtin objects? Node.prototype.nt = function() { return this.nodeType; }
73
3431
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 prototypes. This kind of bugged me, because from other people's code that I've seen in the past, almost all of them use function prototypes. The following also bugged me. Let's say you have a file called main.c with only the main function, and...
31
2435
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
9227
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9145
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9081
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8020
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6676
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 presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5992
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 then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4761
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3206
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2590
muto222
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.