By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
460,030 Members | 1,231 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 460,030 IT Pros & Developers. It's quick & easy.

"this" Keyword Inheritence Workaround

P: 65
Alright, another question to pin on the experts. :D

I have an issue with "this" keyword in this case. The way I got around it before was to use a window property, but in this case I'm trying to keep everything within the context of the object.

So... Basically, this is referring to what I wanted it to refer to before (well, it worked in Mozilla, but not in IE, so I used the window workaround to fit both browsers).

What I want to do apparently is to mimic what IE (gasp) does with attachEvent in other browsers to make this. in a couple of my functions to refer to the object they're a part of, and not the element they were called by.

Problem lines (I think): 95, 96, 120, 219 (the entire function needs to be referenced), 449, 466 (the entire function needs to be referenced), 483, 491, 549, 603 (the entire function needs to be referenced), 623, 676 (the entire function needs to be referenced), 761, 770 (the entire function needs to be referenced), 791 (the entire function needs to be referenced).

Here are those specific lines (in order):
Expand|Select|Wrap|Line Numbers
  1. this.button.addEventListener ('click', this.submitMessage, (false));
  2. this.message.addEventListener ('click', this.character, (false));
  3. setTimeout (this.scanUsers, this.usersUpdateRate);
  4. chat.prototype.client = function ()
  5. setTimeout (this.retrieve, this.historyUpdateRate);
  6. chat.prototype.retrieve = function ()
  7. this.connection.addEventListener ('readystatechange', this.client, (false));
  8. setTimeout (this.retrieve, this.historyUpdateRate);
  9. this.connection.addEventListener ('readystatechange', this.client, (false));
  10. chat.prototype.scanUsers = function ()
  11. setTimeout (this.scanUsers, this.usersUpdateRate);
  12. chat.prototype.bottom = function (starting)
  13. setTimeout (this.bottom, this.scrollSpeed);
  14. chat.prototype.character = function (e)
  15. chat.prototype.submitMessage = function ()
Full library: http://preview.moltx.name/chat_v2/chat.js

What I need is probably not with the function definitions to be changed, but rather how do I make this in those functions refer to the chat object no matter what?
Dec 15 '08 #1
Share this Question
Share on Google+
11 Replies


Dormilich
Expert Mod 5K+
P: 8,639
as you already mentioned, the this keyword in event handlers and window methods doesn't refer to the method's object (quite a good article here: Digital Web Magazine - Scope in JavaScript) but the calling object (element or window). you can reference your methods there with the objects name (e.g. chat.method). you might even want to read about the object literal.

although the article is written in german, its literature reference is worth looking at: Organisation von JavaScripten

regards
Dec 15 '08 #2

rnd me
Expert 100+
P: 427
simply add var that=this, and in your event functions replace the word "this" with "that".

there is less confusion using separate words like that.
Dec 15 '08 #3

gits
Expert Mod 5K+
P: 5,390
the var that = this; fix is the common and probably best way to fix the execution context ... another and a bit more complicated way could be the apply() or call() method ... that are worth a look at for such problems ...

kind regards
Dec 15 '08 #4

P: 65
Alright, I've tried the that = this method, didn't work. Tried that = this (well, chat = this, and library = this) and enclosing the function calls in an anonymous function. Still was getting a "undefined" issue. So I tried doing window.library = this, got half undefined, half not undefined (really confused me there), even with all references to "this" replaced with window.library in all functions except the main one. All to no avail.

I tried the apply and call methods (which I didn't have any clue of how they worked for a while) and neither of those had any success.

Now, I've tried combining both that = this and the call method, which doesn't work, but doesn't cause any errors either. =S

Expand|Select|Wrap|Line Numbers
  1. var chat = this;
  2. setTimeout (function () {chat.retrieve.call (chat);}, this.historyUpdateRate);
Praise be to the one who brings us client-side PHP in all major browsers. =P
Dec 17 '08 #5

Dormilich
Expert Mod 5K+
P: 8,639
just had a look at the javascript file. there's one thing I like to know:

how do you define the chat object?

in the file I see a function chat() which has to be applied to an object. like obj.chat(); giving obj a couple of properties, but I see no prototype or bind.

if you intend chat to be an object there, use the object literal
Expand|Select|Wrap|Line Numbers
  1. obj = {
  2.   property : "value",
  3.   method : function(args) { // code goes here }
  4. };
or
Expand|Select|Wrap|Line Numbers
  1. obj = function() {
  2.   var privat_property = "value";
  3.   function private_method(args) { // code goes here }
  4.   return {
  5.     public_property : "value",
  6.     public_method : function(args) { // code goes here }
  7.   };
  8. }();
regards
Dec 17 '08 #6

P: 65
I'm a little tired at this point, so I'm kind of just trying random things. I updated my code a little bit, so it looks more similar to second example you gave me, and I added a bit of code at the very last line of the chat.js file. I also split the "initiation" into two things rather than one (hence the extra line of code at the very bottom).

I'll look up the way you described on Google tomorrow to give me some more time to study it (I've never seen that kind of syntax used in JavaScript before, I feel like a newbie again), since I can't make any sense of it on a brain that has been active for over 52 hours.
Dec 17 '08 #7

P: 65
Oh, I forgot to include this, as I never gave any way to show the page that is using the chat.js file. So here is how I'm currently calling it.

Expand|Select|Wrap|Line Numbers
  1. window.onload = function ()
  2.     {
  3.         chat.Initialize (
  4.             document.getElementById ("history"),
  5.             "./index.php5?mode=retrieve2&list=history&room=<?php print (str_replace (' ', '+', $room)); ?>&build=<?php print ($build); ?>",
  6.             "./index.php5?mode=update&room=<?php print (str_replace (' ', '+', $room)); ?>&build=<?php print ($build); ?>",
  7.             "<?php print ($username); ?>",
  8.             (2500),
  9.             document.getElementById ("message"),
  10.             document.getElementById ("button"),
  11.             "./index.php5?mode=send2&room=<?php print (str_replace (' ', '+', $room)); ?>&build=<?php print ($build); ?>",
  12.             document.getElementById ("users"),
  13.             "./index.php5?mode=retrieve2&list=users&room=<?php print (str_replace (' ', '+', $room)); ?>&build=<?php print ($build); ?>",
  14.             (15000),
  15.             (1)
  16.         );
  17.     }
Dec 17 '08 #8

Dormilich
Expert Mod 5K+
P: 8,639
usually you initialize an object with its constructor, like
Expand|Select|Wrap|Line Numbers
  1. var chat = new chatObject(//-- values go here --);
not with a prototyped function. and if you use only one object at the page, there's no reason to use prototype at all. object methods can be easily defined in the object constructor.

in Firebug you can have a look at the current DOM. the chat object (along with its members) should show up there. This is a good start for debugging.

regards
Dec 17 '08 #9

gits
Expert Mod 5K+
P: 5,390
the call() and apply() methods are overhead here ... have a look at the following example:

Expand|Select|Wrap|Line Numbers
  1. function OBJ() {
  2.     this.bar = 'foobar';
  3. }
  4.  
  5. OBJ.prototype.foo = function() {
  6.     console.info(this.bar);
  7. }
  8.  
  9. var obj = new OBJ;
  10.  
  11. window.setTimeout(obj.foo, 1000);
  12.  
here you loose the execution context due to the timeout that binds the function to the window implicitly. but you may just use:

Expand|Select|Wrap|Line Numbers
  1. function OBJ() {
  2.     this.bar = 'foobar';
  3. }
  4.  
  5. OBJ.prototype.foo = function() {
  6.     console.info(this.bar);
  7. }
  8.  
  9. var obj = new OBJ;
  10.  
  11. window.setTimeout(function() { obj.foo() }, 1000);
  12.  
where you closure the reference to the instance and so its context with the function. but you could even use:

Expand|Select|Wrap|Line Numbers
  1. function OBJ() {
  2.     this.bar = 'foobar';
  3. }
  4.  
  5. OBJ.prototype.foo = function() {
  6.     console.info(this.bar);
  7. }
  8.  
  9. var obj = new OBJ;
  10.  
  11. window.setTimeout(function() { obj.foo.call(obj) }, 1000);
  12.  
which explictly binds the functioncall to obj again. but now you could even do:

Expand|Select|Wrap|Line Numbers
  1. function OBJ() {
  2.     this.bar = 'foobar';
  3. }
  4.  
  5. OBJ.prototype.foo = function() {
  6.     console.info(this.bar);
  7. }
  8.  
  9. var obj    = new OBJ;
  10. var my_obj = new OBJ;
  11. my_obj.bar = 'my_foobar';
  12.  
  13. window.setTimeout(function() { obj.foo.call(obj) }, 1000);
  14. window.setTimeout(function() { obj.foo.call(my_obj) }, 1000);
  15.  
kind regards

PS: console.info() may be used to test in firebug ... or just replace it with an alert or whatever you want
Dec 17 '08 #10

P: 65
I actually figured out why I was getting no errors. I threw in an alert for each function that was called, and it always stopped at client, and didn't continue to handle. It was because in my haste for a fix, I replaced this.connection with just this.

So actually my object construction method seems to be performing perfectly fine, and this. is inheriting (I think) the way I want it to now. So now I'm just fixing errors, and looking for unexpected behavior. I'll pop back in if I have more trouble. :)
Dec 17 '08 #11

P: 65
Alright, final thing to do to make it all work.

Edit: Solved! I'm going to try this in a different way; using onsubmit in the form.

On line 107, I have an onkeypress event.
Expand|Select|Wrap|Line Numbers
  1. this.message.onkeypress = function () {chat.character (event);}
How would I get "event" in there to act just like it would if I were to put it on the HTML element itself?
Expand|Select|Wrap|Line Numbers
  1. <input onkeypress="chat.character (event); " type="text" />
Dec 17 '08 #12

Post your reply

Sign in to post your reply or Sign up for a free account.