473,804 Members | 2,998 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Assigning methods to objects, and assigning onreadystatecha nge to an XMLHttpRequest -- an inconsistency?

So, the following apparently works as a method of grafting a method
onto an object (using the squarefree JS shell):

obj = { x: 1, inc: null }
result [object Object]
obj.inc = function () { this.x++ }
result function () { this.x++; }
obj.inc()
obj.x
result 2

And by works, I mean that when I create an object, and then assign one
of its properties an anonymous function, the "this" keyword within said
anyonymous function apparently refers to the object itself. Convenient.
I like it.

The problem is, in the context of an XMLHttpRequest object, this
doesn't seem to work as well for me. Again, using the squarefree js
shell:

xhr = new XMLHttpRequest( )
result[object XMLHttpRequest]
xhr.onreadystat echange = function () { alert(this.resp onseText); }
resultfunction () { alert(this.resp onseText); }
xhr.open("GET", "http://www.squarefree. com/shell/shell.html",tru e)

Now, one might think this would produce an alert containing the
text/html of shell.html. But it doesn't. The value of this.responseTe xt
is apparently undefined.

A slight variation reveals an apparent explanation:

xhr.onreadystat echange = function () { alert(this); }
resultfunction () { alert(this); }
xhr.open("GET", "http://www.squarefree. com/shell/shell.html",tru e)

This produces an alert that ... displays the code of the anonymous
function itself.

So, apparently, in this case, the "this" keyword refers to the function
itself, and it would seem I can't graft-on methods that have access to
the other properties of the XMLHttpRequest object. At least via the
"this" keyword.

Can someone help me understand what the differences between the two
situations are?

Also... the reason why I'm interested in this largely has to do with
some vague stylistic discomfort. Much of the code I've seen and written
using XMLHttpRequests uses global / lexically scoped variables to get
information across curly-braces between functions. If I could graft
methods onto the request objects themselves, I think I could cut down
on this. I'm open to other suggestions.

Sep 22 '06 #1
1 2267
weston wrote:
So, the following apparently works as a method of grafting a method
onto an object (using the squarefree JS shell):

obj = { x: 1, inc: null }
result [object Object]
obj.inc = function () { this.x++ }
result function () { this.x++; }
obj.inc()
obj.x
result 2

And by works, I mean that when I create an object, and then
assign one of its properties an anonymous function, the
"this" keyword within said anyonymous function apparently
refers to the object itself. Convenient. I like it.
As expressed, that effect is an illusion as - this - is determined
always, and only, by how a function is called. If you call one as a
method of an object, as you do above, - this - will refer to that
object.
The problem is, in the context of an XMLHttpRequest object,
this doesn't seem to work as well for me. Again, using the
squarefree js shell:

xhr = new XMLHttpRequest( )
result[object XMLHttpRequest]
xhr.onreadystat echange = function () { alert(this.resp onseText); }
resultfunction () { alert(this.resp onseText); }
xhr.open("GET", "http://www.squarefree. com/shell/shell.html",tru e)

Now, one might think this would produce an alert containing
the text/html of shell.html. But it doesn't. The value of
this.responseTe xt is apparently undefined.
The problem is that you don't know how the onreadystatecha nge handler is
being called by the browser so you cannot know in advance what - this -
will refer to. Experimentation reveals that (for IE at least) it is not
called as a method or any particular object.
A slight variation reveals an apparent explanation:

xhr.onreadystat echange = function () { alert(this); }
resultfunction () { alert(this); }
xhr.open("GET", "http://www.squarefree. com/shell/shell.html",tru e)

This produces an alert that ... displays the code of the
anonymous function itself.
I bet that is not universally true.
So, apparently, in this case, the "this" keyword refers
to the function itself, and it would seem I can't
graft-on methods that have access to the other
properties of the XMLHttpRequest object. At least
via the "this" keyword.
Yes, you cannot use - this - practically, so you must provide access to
objects of interest by some other means (and there are plenty of
options).
Can someone help me understand what the differences
between the two situations are?
The difference is between knowing how a function is being called and not
knowing. Generally when you don't know you can work it out by trying,
but if the results are not useful you still have to deal with that.
Also... the reason why I'm interested in this largely
has to do with some vague stylistic discomfort. Much of
the code I've seen and written using XMLHttpRequests
uses global / lexically scoped variables to get information
Globals are not so good, as multiple asynchronous requests will tend to
overwrite them. Exploiting closures (the lexically scoped stuff) is much
better.
across curly-braces between functions.
If I could graft methods onto the request objects
themselves, I think I could cut down on this. I'm
open to other suggestions.
That is quite an 'if' as there is no reason to expect that the request
object can have properties added to it at runtime (except that that is
common in javascript environments) as they are host objects and may not
provide the facility.

Bus since you cannot get - this - to reliably refer to the request
object the question is academic.

Richard.
Sep 22 '06 #2

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

Similar topics

1
8430
by: sams | last post by:
How can I assign a return value of a CGI to a JavaScript variable? Or what is the correct way? <script> var myData = eval(http://somewhere/cgi-bin/data.cgi"); </script> TIA Sam
1
2082
by: Jacob Friis Larsen | last post by:
Anyone know how to let processReqChange know that it is in an object? In Php I can do it like this: array($this, 'function_name'); Any idea for a workaround? /Jacob function ajax () { this.url = '';
7
3361
by: adam | last post by:
i'm working on a portion of a CMS that allows content-admins to browse a product list, and add individual products into the taxonomy by clicking checkboxes next to categories they might belong in. since the taxonomy is a rather long list, i'm hiding and showing divs for the secondary and tertiary links, so when a user clicks on the checkbox for the parent category, the children appear in a second (and third) div, with checkboxes of their...
1
22501
by: akhil.patel | last post by:
I realize that this may have been asked before, but I could not find a definitive answer. function loadXMLDoc(url, MyFunction) { // use native XMLHttpRequest object if (window.XMLHttpRequest) { request = new XMLHttpRequest(); request.onreadystatechange = MyFunction; request.open("GET", url, true);
2
6197
by: jhullu | last post by:
hello, I'm writing a program using XMLHttpRequest that works in the main case on IE and mozilla but this code works only on IE ... why ? probleme is located at mark 'HERE' at the end of code. {__start_of_code__} ('piece' of code) ....
2
21878
by: petermichaux | last post by:
Hi, I thought it is about time I tried writing some JavaScript with XMLHttpRequest instead of just using the Yahoo! UI library. The simple page below works in both Safari and Opera but I don't see the alert in Firefox. Looking in Firefox's firebug plugin, I see that the request is successfully sent and the correct response is received. Any ideas what is wrong? Thank you,
10
11421
by: HugeBob | last post by:
Hi All, I'm having a problem with a web app I'm writing. I have a form for which I'm going to validate one of the fields. I use AJAX to retrieve XML containing a list of valid entries. My app works under IE, oddly enough. But, under Firefox, it seems that the XMLHttpRequest.onreadystatechange method is not being called. The code follows. I'm using synchronous mode because I'm thinking that I want that global variable...
3
9291
pbmods
by: pbmods | last post by:
AN INTRODUCTION TO FUNCTION OBJECTS LEVEL: INTERMEDIATE PREREQS: OBJECTS You've seen it before. You're setting up an XMLHttpRequest call, and you need to execute a function when it returns, so you do something like this: http.onreadystatechange = myAwesomeFunction;
5
6424
by: Heofz | last post by:
Hey all, I've been banging my head against a brick wall on this one for the last 12 hours, and the time has come for me to give up and consult the gurus on this one. The below URL contains a login page, you can test it using the details User: marco Pass: polo This seems to work PERFECTLY in opera, and it works in firefox but ONLY if I have firebug enabled. I don't care about IE for now, I'll sort that out later.
0
9706
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9579
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10332
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
9152
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
7620
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
6853
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
4300
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
3820
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2991
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.