473,737 Members | 5,412 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

problem with "this" and context

I am having a problem with the use of "this". Maybe someone can help
me out here, let me know if I am doing this wrong:
Lets say I have an object MyObject, which has local variables, and some
methods. One of the local variables is an HTML input box. On
mousedown I want to execute some code like this:
function MyObject(inputF ieldID){
// get the HTML element
this.InputField = document.getEle mentById(inputF ieldID);
// local variable
this.MyID = inputFieldID;
// function trying to run
this.MyFunction = function(){
alert(this.MyID );
}

this.InputField .onkeydown = this.MyFunction ;

}
Now when you keydown inside the input textbox it errors because inside
the MyFunction function "this" doesn't refer to the object MyObject,
but rather to the Input element.

The only workaround I have found is to give the InputField a reference
to its owner so you have:

this.InputField .MyObject = this;

And then when your MyFunction becomes:
this.MyFunction = function(){
alert(this.MyOb ject.MyID);
}
That works, but it seems like a pain to have to carry those references.

Is there another way to do this?

Aug 8 '05 #1
2 1646
"cmay" <cm**@walshgrou p.com> writes:
I am having a problem with the use of "this". Maybe someone can help
me out here, let me know if I am doing this wrong: Lets say I have an object MyObject, which has local variables, and some
methods.
Objects don't have local variables, so I guess you just mean
properties.
One of the local variables is an HTML input box.
A DOM HTMLInputElemen t object.
function MyObject(inputF ieldID){ .... this.MyFunction = function(){
alert(this.MyID );
} this.InputField .onkeydown = this.MyFunction ; ....
Now when you keydown inside the input textbox it errors because inside
the MyFunction function "this" doesn't refer to the object MyObject,
but rather to the Input element.
Yes. The "this" operator refers to the base object of the property
reference that was called. When the onkeydown property of the input
element is called, "this" will refer to the input element during
the execution of the body of the function. That means that
alert(this.MyID )
will alert the undefined value.
The only workaround I have found is to give the InputField a reference
to its owner so you have:

this.InputField .MyObject = this;
Refernces between DOM objects and other objects is known to cause
memory leak in IE. You are already doing that, but no need to compound
the problem :)
And then when your MyFunction becomes:
this.MyFunction = function(){
alert(this.MyOb ject.MyID);
} Is there another way to do this?


Try:

var self = this;
this.MyFunction = function() {
alert(self.MyID );
}

The "self" variable will copy the refrence to the MyObject instance,
so that it is available to the function.

/L
--
Lasse Reichstein Nielsen - lr*@hotpop.com
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleD OM.html>
'Faith without judgement merely degrades the spirit divine.'
Aug 9 '05 #2
Great, thanks.

Aug 10 '05 #3

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

Similar topics

1
1458
by: lawrence | last post by:
I'm trying to gain a better understanding of javascript by studying examples. I noticed this in an online tutorial. I don't get the use of "this". >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> You might want to add some event handler for an event to an element to which there is already an event handler attached. That is possible by storing the old event handler somewhere and then writing a new function which calls the old event handler.
9
2184
by: aden | last post by:
I have read the years-old threads on this topic, but I wanted to confirm what they suggest. . . Can the this pointer EVER point to a type different from the class that contains the member function that the this pointer is being used in? That is, is the type of the this pointer always determined entirely syntactically (and never dynamically)? Example: if a member function is invoked on an object of class Apple (appleobj.drip_it() ),...
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.
2
1563
by: Bryan | last post by:
Hello all, Can anyone explain when one should use the "document" object and when one should use the "this" object? Also, is the "self" object the same as the "document" or "this" object?
1
1191
by: Peter Rilling | last post by:
Hi. I am using Atlas and hooking a load event using add_load(...). This is being called from the constructor of an object being created, so it is within the context of an object (where 'this' is recognized). I want the handler to be an instance method on the object instance. Sys.Application.add_load( this._onLoad ) );
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) {
8
4545
by: =?Utf-8?B?VHJlY2l1cw==?= | last post by:
Hello, Newsgroupians: I have a large class with a lot of member variables. I also have a function in the class that I would like to change ALL Of the member variables. I am trying to assign "this" to the result, but I always get the error message, "Cannot assign to '<this>' because it is read-only." I've been searching on the Internet, and I notice some C# code is violating this rule. Perhaps their code is wrong.
6
1939
by: andrew.bell.ia | last post by:
Hi, I've got this very simple code that I don't understand (output follows code). Why does access to the _field variable fail without the "this"? I thought that once _field was added to the prototype object (an Integer, in this case), it was just like any other property of the object (like _val, which is set in the Integer ctor).
11
1569
by: moltendorf | last post by:
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...
0
8786
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
9334
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
9258
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
9207
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
8207
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...
0
6052
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
4823
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2744
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2192
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.