473,782 Members | 2,423 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Question about function objects vs object literals?

Hi all,

I'm stuck in a situation where I need help. Any help will be highly
appreciated. I've created an object, after creating the object, I'm
assigning one of its functions to an event handler i.e. to onBlur
event of Text-area. Problem is that when I try to access object
properties from the handler function, I cannot access them in some
cases and get a value of undefined. Here is the sample code that I'm
trying

METHOD A:
---------
Expand|Select|Wrap|Line Numbers
  1. function TestObj(src, dest){
  2.  
  3. this.src = src;
  4. this.dest= dest;
  5. this.count = 500;
  6. }
  7.  
  8. TestObj.prototype.display=function(){
  9.  
  10. //following displays 'undefined'
  11. alert("Source ="+this.src+", Destination ="+this.dest);
  12. //following also displays 'undefined'
  13. alert('Count ='+this.count);
  14. }
and here is how I'm using the above (using JQuery)

Expand|Select|Wrap|Line Numbers
  1. $(document).read(function(){
  2. var t=new TestObj(50,100);
  3. $("#tarea1").blur(t.display);
  4. });
But when I do the following using Object literal , things seem to work
OK

METHOD B
--------

Expand|Select|Wrap|Line Numbers
  1. var TestObj={
  2.  
  3. display:function(src,dest){
  4.  
  5. return function(){
  6. alert("Source ="+this.src+", Destination ="+this.dest);
  7. }
  8.  
  9. }
  10. };
  11.  
  12. $(document).read(function(){
  13. //This works and I see values of 50 & 100 in the alert box
  14. $("#tarea1").blur(TestObj.display(50,100));
  15. });
Amazingly following also works :)

METHOD C:
---------
Expand|Select|Wrap|Line Numbers
  1. function TestObj(){
  2.  
  3. }
  4.  
  5. TestObj.prototype.display=function(src,dest){
  6.  
  7. return function(){
  8. alert("Source ="+this.src+", Destination ="+this.dest);
  9. }
  10.  
  11. }
and here is how I'm using the above (using JQuery)

Expand|Select|Wrap|Line Numbers
  1. $(document).read(function(){
  2.  
  3. var t=new TestObj();
  4.  
  5. $("#tarea1").blur(t.display(5,10));
  6.  
  7. });
  8.  
Actually, I want to go with the Function object approach mentioned
under METHOD C, but I'm also trying to avoid the closure in " display
" function as I've read on Internet that it can cause memory leaks in
IE6. Any ideas on how to make METHOD C work while avoiding a closure.

Also, if you can give a reason as to why METHOD A isn't working that
will be highly appreciated.
Thanks in advance.

Regards,
Oltmans
Jun 30 '08 #1
2 1241
On Jun 30, 11:16 am, Oltmans <rolf.oltm...@g mail.comwrote:
Hi all,

I'm stuck in a situation where I need help. Any help will be highly
appreciated. I've created an object, after creating the object, I'm
assigning one of its functions to an event handler i.e. to onBlur
event of Text-area. Problem is that when I try to access object
properties from the handler function, I cannot access them in some
cases and get a value of undefined. Here is the sample code that I'm
trying

METHOD A:
---------
Expand|Select|Wrap|Line Numbers
  1. function TestObj(src, dest){
  2.  
  3. this.src = src;
  4. this.dest= dest;
  5. this.count = 500;
  6.  
  7. }
  8.  
  9. TestObj.prototype.display=function(){
  10.  
  11. //following displays 'undefined'
  12. alert("Source ="+this.src+", Destination ="+this.dest);
  13. //following also displays 'undefined'
  14. alert('Count ='+this.count);
  15.  
  16. }
and here is how I'm using the above (using JQuery)

Expand|Select|Wrap|Line Numbers
  1. $(document).read(function(){
  2. var t=new TestObj(50,100);
  3. $("#tarea1").blur(t.display);
  4. });
I'm not a jQuery user but my guess is that "this" is not being set
properly when the "display" function is called. I'd guess that jQuery
set's "this" to be the DOM element that has blurred when the event
fires. You want "this" to be the "t" object. Perhaps try the
following.

Expand|Select|Wrap|Line Numbers
  1. $(document).read(function() {
  2. var t=new TestObj(50,100);
  3. $("#tarea1").blur(function() {t.display();});
  4. });

But when I do the following using Object literal , things seem to work
OK

METHOD B
--------

Expand|Select|Wrap|Line Numbers
  1. var TestObj={
  2.  
  3. display:function(src,dest){
  4.  
  5.         return function(){
  6.                 alert("Source ="+this.src+", Destination ="+this.dest);
  7.         }
  8.  
  9. }
  10. };
  11.  
  12. $(document).read(function(){
  13. //This works and I see values of 50 & 100 in the alert box
  14. $("#tarea1").blur(TestObj.display(50,100));
  15.  
  16. });
I wouldn't have thought that the above would work. do you have "src"
and "dest" attributes set on the tarea1 element or global variables
also?

Amazingly following also works :)

METHOD C:
---------
Expand|Select|Wrap|Line Numbers
  1. function TestObj(){
  2.  
  3. }
  4.  
  5. TestObj.prototype.display=function(src,dest){
  6.  
  7. return function(){
  8.         alert("Source ="+this.src+", Destination ="+this.dest);
  9.         }
  10.  
  11. }
  12.  
  13. and here is how I'm using the above (using JQuery)
  14.  
  15. $(document).read(function(){
  16.  
  17. var t=new TestObj();
  18.  
  19. $("#tarea1").blur(t.display(5,10));
  20.  
  21. });
Again something seems odd here. There is never any setting of the
this.src and this.dest properties so how do they print properly?

Actually, I want to go with the Function object approach mentioned
under METHOD C, but I'm also trying to avoid the closure in " display
" function as I've read on Internet that it can cause memory leaks in
IE6.
I imagine that jQuery has other workarounds for the IE memory leak
issues. Most event libraries do some clean up when the page unloads
and provide an API for "cleaning" elements of all their event
handlers.
Any ideas on how to make METHOD C work while avoiding a closure.
When registering event handler functions there is almost always
closures involved somewhere so the event handler function either knows
the correct "this" value or has access to other values it needs. The
problem with memory leaks is if the event handler function has a
reference to the DOM element the function observes. It doesn't look
like you have that problem in Method C.

How I might write this...

Expand|Select|Wrap|Line Numbers
  1. var handlerGenerator = function(src, dest) {
  2. return function() {
  3. alert("Source =" + src + ", Destination =" + dest);
  4. };
  5. };
  6.  
  7. $(document).read(function(){
  8. $("#tarea1").blur(handlerGenerator(5,10));
  9. });
  10.  
Peter
Jun 30 '08 #2
Expand|Select|Wrap|Line Numbers
  1. var t=new TestObj(50,100);
  2. $("#tarea1").blur(t.display);  <-- here your passing the function, no
  3. way jQuery knows about 't' object
What you want to do is,
Expand|Select|Wrap|Line Numbers
  1. $("#tarea1").blur(function(){t.display();});
This is not jQuery fault, this is how JS works.


or you could do something like:

Expand|Select|Wrap|Line Numbers
  1. function TestObj(src, dest){
  2. var me=this; // save what 'this' is pointing to, so you can use it
  3. on a closure
  4. me.src = src;
  5. me.dest= dest;
  6. me.count = 500;
  7.  
  8. me.display=function(){
  9. //following displays 'undefined'
  10. alert("Source ="+me.src+", Destination ="+me.dest);
  11. //following also displays 'undefined'
  12. alert('Count ='+me.count);
  13. };
  14. };
  15.  
  16. var t=new TestObj(50,100);
  17. $("#tarea1").blur(t.display);// <-- should work now, here  me!=this
  18. but  me==t
Jun 30 '08 #3

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

Similar topics

15
417
by: Alex | last post by:
could somebody tell me the difference between those two styles: function abc(var1, var2){ /* logic in here */ } and abc = function(var1, var2){ /* logic in here */ }; When / why would I use one over the other?
9
1437
by: gor | last post by:
I would like to find out how javascript can change some text (string) inside <DIV> tag with event onClick. That i want to solve with function callWrite(); ... so you can see in the code. The thing should be simple, not to me ofcourse. I dont have a clue, but maybe method getElementById may have somthing to do with solving my problem. I dont know. html>
21
4082
by: Jon Slaughter | last post by:
I have a class that is basicaly duplicated throughout several files with only members names changing according to the class name yet with virtually the exact same coding going on. e.g. class A { std::vector<B*> Bs; public:
17
1999
by: herrcho | last post by:
#include <stdio.h> int main() { int i; char *p="sarang"; for(i=0;i<4;i++) printf("%c",*(p+i)); printf("\n"); for(i=0;i<4;i++)
6
2020
by: kobu.selva | last post by:
I was recently part of a little debate on the issue of whether constants and string literals are considered "data objects" in C. I'm more confused now than before. I was always under the understanding that only "named" storage areas(from the standard) were data objects. Since constants and string literals don't have lvalues, they can't be data objects. Yet, I was shown the first page of chapter 2 in K&R2, which states that variables...
2
2517
by: JJA | last post by:
I'm looking at some code I do not understand: var icons = new Array(); icons = new GIcon(); icons.image = "somefilename.png"; I read this as an array of icons is being built. An element of the array is an object itself but what is this syntax of the consecutive double quotes inside the brackets ?
27
2568
by: SasQ | last post by:
Hello. I wonder if literal constants are objects, or they're only "naked" values not contained in any object? I have read that literal constants may not to be allocated by the compiler. If the Standard is saying that "object is a region of storage", I deduce from that that literal constants aren't objects because they may not be alocated as regions of storage in the memory.
4
4882
by: =?ISO-8859-15?Q?Jean=2DFran=E7ois?= Lemaire | last post by:
Hello all, I'm learning C and I still am struggling to understand some basic concepts. For example, I read in the standard that with functions such as strcpy, 'If copying takes place between objects that overlap, the behavior is undefined.' But how can I be sure that they don't overlap? For example, if I write this: char string1 = "overlap";
8
4578
by: minseokoh | last post by:
Hi, Could someone explain why "const" is located after the function name and what it means? inline unsigned char *access(int off) const { if (off < 0) abort(); return (&bits_); }
0
10313
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
10147
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
10081
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
9946
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
7494
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
6735
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
5511
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4044
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
3
2875
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.