473,747 Members | 2,754 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

"this" Keyword Inheritence Workaround

65 New Member
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
11 1570
Dormilich
8,658 Recognized Expert Moderator Expert
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
427 Recognized Expert Contributor
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
5,390 Recognized Expert Moderator Expert
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
moltendorf
65 New Member
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
8,658 Recognized Expert Moderator Expert
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
moltendorf
65 New Member
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
moltendorf
65 New Member
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
8,658 Recognized Expert Moderator Expert
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
5,390 Recognized Expert Moderator Expert
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

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

Similar topics

6
1579
by: Anders Borum | last post by:
Hello! I'm wondering what the recommendations are for using the "this" keyword? The problem is that I really like to use the "this" keyword, but it tends to make the code more verbose (which some don't like). Your oppinion please? ... internal void PageDeleted(Page page) {
6
2714
by: Marty | last post by:
Hi, I have a class that I modified to be static. It is now a public sealed class and all function are static, no more constructor but a init() function to do the constructor job. This class inherit from a QuickFix.Application class. I have this object: private static SocketInitiator qfxInitiator; When instantiated, its constructor need a "QuickFix.Application" object.
5
2475
by: ChrisB | last post by:
Hello: An object that is a field in another object has a constructor that requires a reference to the containing object: // object fields ChildObject childObject = new ChildObject(this); When attempting to compile this code, a message is returned that states that the "this" keyword is not available in this context.
7
2249
by: relient | last post by:
Question: Why can't you access a private inherited field from a base class in a derived class? I have a *theory* of how this works, of which, I'm not completely sure of but makes logical sense to me. So, I'm here for an answer (more of a confirmation), hopefully. First let me say that I know people keep saying; it doesn't work because the member "is a private". I believe there's more to it than just simply that... Theory: You inherit,...
0
1440
by: gahagan | last post by:
If you encounter this error, most likely one of the controls you're trying to cut/paste is a combo box with a longer-than-average 'Row Source' value. That, apparently, is the problem. Shorter Row Source values don't seem to be a problem. (I don't have time to figure out at what length the error triggers.) Workaround: Remove the Row Source (you can cut/paste the text somewhere else), then try cutting/pasting the control(s) again. Then...
1
2179
by: goe | last post by:
Hi, Im my function I need to use focus() and select() based on the "this" keyword. example: onchange="validate(this)" function validate(input) {
5
2236
by: Jeremy | last post by:
Is there any good reading about pitfalls of scoping when using events? Here is my specific issue: function MyType() { this.foo = "bar"; this.textbox = document.createElement("input"); this.textbox.type = "text"; this.textbox.addEventListener("blur", this.doThings, false);
4
1474
by: pbd22 | last post by:
Hi. I am wondering what do I replace the "this" statement with to get the appropriate container/response. When I try: cal.prototype.dates(cal.days.day); I get
5
1513
by: Polaris431 | last post by:
I notice that the Dataset designer generates code for properties that look like this: public string ID { get { try { return ((string) (this)); } catch (System.InvalidCastException e) {
0
8978
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
8818
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
9522
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
9353
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
9222
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...
1
6790
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
4588
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 last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
2
2771
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2203
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.