473,789 Members | 2,926 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

OO javascript... this doesn't appear to point to the object

I'm trying to utilized a more object-oriented approach to managing
window events in javascript. Thus, I am creating a "controller " object
to handle events and interact with the server. However, I apparently
don't fully understand what "this" refers to. In the code below I was
expecting that when the button was clicked (handleDeleteBu ttonClicked
function) that "this" would be pointing at a ViewController object.
Instead it was the Button (HtmlInputEleme nt).

Can somebody help me understand?

<html>
<head>
<script>
/* Constructor */
function ViewController( ) {
this.foo = "bar";
}

/* delete button handler */
ViewController. prototype.handl eDeleteButtonCl icked = function() {
window.alert("d elete clicked, this=" + this + " this.foo= " +
this.foo);
};

/* initializer */
ViewController. prototype.initi alize = function() {
document.getEle mentById("delet e-button").onclic k =
this.handleDele teButtonClicked ;
};
</script>
</head>
<body onload="javascr ipt:new ViewController( ).initialize(); ">
<input id="delete-button" type="button" value="Delete">
</body>
</html>

Oct 20 '06 #1
28 2130
ensemble wrote:
I'm trying to utilized a more object-oriented approach to managing
window events in javascript. Thus, I am creating a "controller "
object to handle events and interact with the server. However, I
apparently don't fully understand what "this" refers to.
Then search the Google Groups archives for phrases like "the this
operator" and such. It has been discussed many times in the past.

Be careful to ignore anything a poster named "VK" has to say on the matter.

[snip]

Mike
Oct 20 '06 #2
VK
ensemble wrote:
I'm trying to utilized a more object-oriented approach to managing
window events in javascript. Thus, I am creating a "controller " object
to handle events and interact with the server.
IMHO your code looks more as an attempt to reproduce other languages
weaknesses and workarounds in javascript. The javascript event model
has enough of its own headaches to add Java's or C++'s ones into it ;-)

<html>
<head>
<titlemake KISS - then OOP ! </title>
<meta http-equiv="Content-Type"
content="text/html; charset=iso-8859-1">

<script type="text/javascript">

function EventListener(o bj) {

// Lightweight constructor protection:
if (((window) && (this == window))
|| (!obj) || (!obj.tagName)) {
return new Boolean(false);
}

obj.JSInstance = this;

this.foo = 'foo';

for (var i=1; i<arguments.len gth; i++) {
obj[arguments[i]] = EventListener[arguments[i]];
}
}

EventListener.o nmouseover = function() {
this.style.back groundColor = 'yellow';
}

EventListener.o nmouseout = function() {
this.style.back groundColor = '';
}

EventListener.o nclick = function() {
alert(this.JSIn stance.foo);
}
function init() {
new EventListener(d ocument.getElem entById('btnAdd '),
'onmouseover', 'onmouseout');

new EventListener(d ocument.getElem entById('btnEdi t'),
'onclick' );

new EventListener(d ocument.getElem entById('btnDel ete'),
'onmouseover', 'onmouseout', 'onclick' );
}
window.onload = init;
</script>
</head>

<body>
<button id="btnAdd" type="button">A dd</button>
<button id="btnEdit" type="button">E dit</button>
<button id="btnDelete" type="button">D elete</button>

</body>
</html>
However, I apparently
don't fully understand what "this" refers to.
[this] refers to the *current object* (or by ECMAScript specs it points
to "the object pointed by [this] keyword", which is cool to know but
not very helpful :-)

Current object can be:
1) Global object (most of the time)
2) New object instance (in constructor)
3) Object instance owning the called method (more rarely than it should
IMHO)
4) Other object instance transferred by call() or apply() methods
5) Equivalent of *default object* in with (this) {...} construct
6) DOM element received the event in intrinsic method handlers.

By the rules of good show I placed your case at the very end :-)

Oct 21 '06 #3

ensemble wrote:
I'm trying to utilized a more object-oriented approach to managing
window events in javascript. Thus, I am creating a "controller " object
to handle events and interact with the server. However, I apparently
don't fully understand what "this" refers to. In the code below I was
expecting that when the button was clicked (handleDeleteBu ttonClicked
function) that "this" would be pointing at a ViewController object.
Instead it was the Button (HtmlInputEleme nt).

Can somebody help me understand?

<html>
<head>
<script>
/* Constructor */
function ViewController( ) {
this.foo = "bar";
}

/* delete button handler */
ViewController. prototype.handl eDeleteButtonCl icked = function() {
window.alert("d elete clicked, this=" + this + " this.foo= " +
this.foo);
};

/* initializer */
ViewController. prototype.initi alize = function() {
document.getEle mentById("delet e-button").onclic k =
this.handleDele teButtonClicked ;
};
</script>
</head>
<body onload="javascr ipt:new ViewController( ).initialize(); ">
<input id="delete-button" type="button" value="Delete">
</body>
</html>

More research got me to an answer: "this" does not always refer to the
object for which you work. Specifically when called by an event
handler the called function will have "this" set to the control for
whom the event was generated (e.g., button). The original objective
(having a controller object) can be resolved by one level of
indirection:

<html>
<head>
<script>
function initialize() {
var controller = new ViewController( );
document.getEle mentById("delet e-button").onclic k = function() {
controller.hand leDeleteButtonC licked();
}
}

/* constructor */
function ViewController( ) {
this.foo = "bar";
}

/* delete button handler */
ViewController. prototype.handl eDeleteButtonCl icked = function() {
window.alert("d elete clicked, this' constructor=" +
this.constructo r);
};

</script>
</head>
<body onload="javascr ipt:initialize( );">
<input id="delete-button" type="button" value="Delete">
</body>
</html>

Oct 21 '06 #4

VK wrote:
ensemble wrote:
I'm trying to utilized a more object-oriented approach to managing
window events in javascript. Thus, I am creating a "controller " object
to handle events and interact with the server.

IMHO your code looks more as an attempt to reproduce other languages
weaknesses and workarounds in javascript. The javascript event model
has enough of its own headaches to add Java's or C++'s ones into it ;-)

<html>
<head>
<titlemake KISS - then OOP ! </title>
<meta http-equiv="Content-Type"
content="text/html; charset=iso-8859-1">

<script type="text/javascript">

function EventListener(o bj) {

// Lightweight constructor protection:
if (((window) && (this == window))
|| (!obj) || (!obj.tagName)) {
return new Boolean(false);
}

obj.JSInstance = this;

this.foo = 'foo';

for (var i=1; i<arguments.len gth; i++) {
obj[arguments[i]] = EventListener[arguments[i]];
}
}

EventListener.o nmouseover = function() {
this.style.back groundColor = 'yellow';
}

EventListener.o nmouseout = function() {
this.style.back groundColor = '';
}

EventListener.o nclick = function() {
alert(this.JSIn stance.foo);
}
function init() {
new EventListener(d ocument.getElem entById('btnAdd '),
'onmouseover', 'onmouseout');

new EventListener(d ocument.getElem entById('btnEdi t'),
'onclick' );

new EventListener(d ocument.getElem entById('btnDel ete'),
'onmouseover', 'onmouseout', 'onclick' );
}
window.onload = init;
</script>
</head>

<body>
<button id="btnAdd" type="button">A dd</button>
<button id="btnEdit" type="button">E dit</button>
<button id="btnDelete" type="button">D elete</button>

</body>
</html>
However, I apparently
don't fully understand what "this" refers to.

[this] refers to the *current object* (or by ECMAScript specs it points
to "the object pointed by [this] keyword", which is cool to know but
not very helpful :-)

Current object can be:
1) Global object (most of the time)
2) New object instance (in constructor)
3) Object instance owning the called method (more rarely than it should
IMHO)
4) Other object instance transferred by call() or apply() methods
5) Equivalent of *default object* in with (this) {...} construct
6) DOM element received the event in intrinsic method handlers.

By the rules of good show I placed your case at the very end :-)
Hi VK -
I'm curious to more about your comment "IMHO your code looks more as an
attempt to reproduce other languages weaknesses and workarounds in
javascript." I haven't done a lot of javascript progamming. However,
I'm interested in apply object oriented approaches to this environment.
GUIs were originally developed using OO languages and it seems natural
to me to apply the same principals here. I'm sure you are aware of all
of the literature being introduced right now on the topic of OO and
javascript development.

It sounds like you might have taken this path yourself and found it was
more frustrating than beneficial? Would be interested in your views....

Oct 21 '06 #5
TC

ensemble wrote:
GUIs were originally developed using OO languages

Uh, say what? GUIs existed before the notion of object oriented
languages had even been thought of!

TC (MVP MSAccess)
http://tc2.atspace.com

Oct 21 '06 #6
TC

TC wrote:
ensemble wrote:
GUIs were originally developed using OO languages


Uh, say what? GUIs existed before the notion of object oriented
languages had even been thought of!
Hmm, perhaps I should qualify that. Certainly there were graphic
terminals back in the 1960's. These could display (and allow for entry
of) information, somewhat like a modern GUI. But they did not have
mice, or allow for common modern GUI features like drag & drop. So I
guess they were not GUIs in the modern sense of the word.

TC (MVP MSAccess)
http://tc2.atspace.com

Oct 21 '06 #7
ensemble wrote:

[snip]
I'm curious to more about your comment "IMHO your code looks more as
an attempt to reproduce other languages weaknesses and workarounds in
javascript."
There is a growing movement to make ECMAScript and its implementations
look like other languages - Python, for example. One problem is that
these wrappers invite the assumption that because the two languages now
look like one another, they act in the same way, too. This reasoning is
flawed and unproductive: understanding the real, underlying language is
the only way to really appreciate behaviour.
I haven't done a lot of javascript progamming. However, I'm
interested in apply object oriented approaches to this environment.
Do keep in mind the practicality of OO and ECMAScript. There is
sometimes little point in developing an OO solution to a problem, and
doing so only adds bloat. If there is a real return on investment from
taking an OO path, then by all means do so, but think if the benefits
are marginal.

[snip]

Mike
Oct 21 '06 #8
TC wrote:
TC wrote:
>ensemble wrote:
>>GUIs were originally developed using OO languages

Uh, say what? GUIs existed before the notion of object oriented
languages had even been thought of!

Hmm, perhaps I should qualify that. Certainly there were graphic
terminals back in the 1960's. These could display (and allow for entry
of) information, somewhat like a modern GUI. But they did not have
mice, or allow for common modern GUI features like drag & drop. So I
guess they were not GUIs in the modern sense of the word.
They had light pens that were functionally equivalent to mice, and used
drag and drop in graphics applications (drag the chair from the
furniture library to the conference room, drag the resistor from the
component library and insert it in the circuit, etc., etc.). They were
much too expensive to use as word processors, etc..

--
John W. Kennedy
"The blind rulers of Logres
Nourished the land on a fallacy of rational virtue."
-- Charles Williams. "Taliessin through Logres: Prelude"
Oct 22 '06 #9
TC wrote:
ensemble wrote:
GUIs were originally developed using OO languages


Uh, say what? GUIs existed before the notion of object oriented
languages had even been thought of!
Without a clear definition of what constitutes a GUI and an OO
language, that's not much more than idle boast. While the definitional
debate in regard to GUIs could rage for ages, there seems to be
agreement that SIMULA I (1962) was the first OO language.

<URL:
http://heim.ifi.uio.no/~kristen/FORS..._OO_start.html >

Probably the first interface that implemented most of the fundamental
principles of a modern GUI was oNLine, creation of which started in
1962, although it wasn't revealed to the world until 1968.

<URL: http://www.kernelthread.com/mac/oshistory/2.html >

Therefore to claim that GUI's predate OO languages seems incorrect,
though I'd like to note that you don't need an OO language to write OO
programs, or to write a GUI.
--
Rob

Oct 22 '06 #10

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

Similar topics

53
5748
by: Cardman | last post by:
Greetings, I am trying to solve a problem that has been inflicting my self created Order Forms for a long time, where the problem is that as I cannot reproduce this error myself, then it is difficult to know what is going on. One of these Order Forms you can see here... http://www.cardman.co.uk/orderform.php3
27
2278
by: C Gillespie | last post by:
Dear All, Hopefully I have a simple problem. Basically, I just want to alter some text with JS. Here is some of my test code: <snip> <script type="text/javascript"> var tmp='a';
22
4648
by: VK | last post by:
A while ago I proposed to update info in the group FAQ section, but I dropped the discussion using the approach "No matter what color the cat is as long as it still hounts the mice". Over the last month I had enough of extra proof that the cat doesn't hount mice anymore in more and more situations. And the surrent sicretisme among array and hash is the base for it. I summarized all points in this article:...
136
9460
by: Matt Kruse | last post by:
http://www.JavascriptToolbox.com/bestpractices/ I started writing this up as a guide for some people who were looking for general tips on how to do things the 'right way' with Javascript. Their code was littered with document.all and eval, for example, and I wanted to create a practical list of best practices that they could easily put to use. The above URL is version 1.0 (draft) that resulted. IMO, it is not a replacement for the FAQ,...
104
17013
by: Leszek | last post by:
Hi. Is it possible in javascript to operate on an array without knowing how mamy elements it has? What i want to do is sending an array to a script, and this script should add all values from that array Could you show me a little example how to do this? Thanks.
11
3323
by: admin | last post by:
Hi all, First time poster here... I'm a webmaster and I'd like to add a simple script to my website which will allow users to fill in a brief multiple choice questionaire, and then provide a 'thoughful' suggestion based on their answers. In terms of the logic involved with the actual script: I've mulled it over and thoroughly broken my brain, trying to devise a complicated 'scoring system' (with different answers giving different...
13
2138
by: Andy Baxter | last post by:
Can anyone recommend a good online guide to using objects in javascript? The book I bought (DHTML Utopia) suggests using objects to keep the code clean and stop namespace clashes between different parts of the code, but as far as I can see, the way objects work in javascript is quite awkward. I had it working the way they suggest in the book, and it was going OK until I wanted to call one object method from another - I couldn't find a...
6
1911
by: drec | last post by:
I am just learning Javascript and I would like to create a basic form that gives me two options. This will be using either checkbox or radio input type, however I would like the second option to allow the user to type in a value. Also, I would like the 2nd option only editable if the button for that option is selected. All I can seem to find is basic examples of forms, and none of which have this feature. The form would look something...
18
1932
by: Tom Cole | last post by:
I'm working on a small Ajax request library to simplify some tasks that I will be taking on shortly. For the most part everything works fine, however I seem to have some issues when running two requests at the same time. The first one stops execution as the second continues. If I place either an alert between the two requests or run the second through a setTimeout of only 1 millisecond, they both work. You can see a working example here:...
0
10410
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10200
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...
0
9984
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
9020
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
7529
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
6769
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();...
1
4093
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
3701
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2909
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.