473,785 Members | 2,789 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

setTimeout within the context of an Object loses context.

I am calling setTimeout within the context of an object, and whilst this exists, it
refuses to be passed along to the function I call. For example:

$elemById('id') .change = function()
{
// the function returns the object itself, 'this' exists
alert(this); // [object HTMLSelectEleme nt]
setTimeout('ale rt(this);',1000 ); // [object Window]
}

So, obviously there is something going on that I have not yet learned to deal with.
First, I went with assigning the object (this) to a variable. When I call it, I get
"variable is not defined" making me think that more than just dereferencing (the
reference's scope changing) is going on.

So, what am I missing?

-Lost
Mar 23 '07 #1
7 6260
Yes indeed the 'this' scope does change, since 'this' is always the evented
caller, or the caller object to which the event/call occurring defaults to.
setTimeout() is a built-in object of window, or window.setTimeo ut(), and within
this scope

window.setTimeo ut('alert(this) ;',1000); // [object Window]

will be corrrect :)

alert(this); // [object HTMLSelectEleme nt] // at the scope of the anonymous
function, will address, the object to where such function object, 'change', is
a member of.

You can always use a local var, to keep it within the scope, kinda cheesy as
it's, _this=this; setTimeout('ale rt(_this);',100 0);

or such
Danny
-Lost wrote:
I am calling setTimeout within the context of an object, and whilst this
exists, it
refuses to be passed along to the function I call. For example:

$elemById('id') .change = function()
{
// the function returns the object itself, 'this' exists
alert(this); // [object HTMLSelectEleme nt]
setTimeout('ale rt(this);',1000 ); // [object Window]
}

So, obviously there is something going on that I have not yet learned to deal
with.
First, I went with assigning the object (this) to a variable. When I call it,
I get "variable is not defined" making me think that more than just
dereferencing (the reference's scope changing) is going on.

So, what am I missing?

-Lost
Mar 23 '07 #2
-Lost wrote:
>
>I am calling setTimeout within the context of an object, and whilst this
exists, it
refuses to be passed along to the function I call. For example:

$elemById('id' ).change = function()
{
// the function returns the object itself, 'this' exists
alert(this); // [object HTMLSelectEleme nt]
setTimeout('ale rt(this);',1000 ); // [object Window]
}

So, obviously there is something going on that I have not yet learned to deal
with.
First, I went with assigning the object (this) to a variable. When I call it,
I get "variable is not defined" making me think that more than just
dereferencin g (the reference's scope changing) is going on.

So, what am I missing?
"Danny" <da*******@blue bottle.comwrote in message
news:Jl******** *******@newssvr 25.news.prodigy .net...
Yes indeed the 'this' scope does change, since 'this' is always the evented
caller, or the caller object to which the event/call occurring defaults to.
setTimeout() is a built-in object of window, or window.setTimeo ut(), and within
this scope

window.setTimeo ut('alert(this) ;',1000); // [object Window]
Ah, OK, that makes sense.
will be corrrect :)
However, if you were implying that changing it to window.setTimeo ut() fixes it, it does
not.
alert(this); // [object HTMLSelectEleme nt] // at the scope of the anonymous
function, will address, the object to where such function object, 'change', is
a member of.
I did not understand this at all.
You can always use a local var, to keep it within the scope, kinda cheesy as
it's, _this=this; setTimeout('ale rt(_this);',100 0);

or such
I have tried assigning it to a variable (like I said) and I always get "variable is not
defined."

-Lost
Mar 23 '07 #3
"-Lost" <mi*********@co mcast.netwrote in message
news:lb******** *************** *******@comcast .com...
>-Lost wrote:
>You can always use a local var, to keep it within the scope, kinda cheesy as
it's, _this=this; setTimeout('ale rt(_this);',100 0);

or such

I have tried assigning it to a variable (like I said) and I always get "variable is not
defined."
Hrmm... I declared the variable with the var keyword and it appears within the context of
this object scope, caused problems. It may have something to do with the library I am
using (as I know you can declare variables within an object scope as local).

-Lost
Mar 23 '07 #4
On Mar 23, 1:29 am, "-Lost" <missed-s...@comcast.ne twrote:
-Lost wrote:
I am calling setTimeout within the context of an object, and whilst this
exists, it
refuses to be passed along to the function I call. For example:
>
You can always use a local var, to keep it within the scope, kinda cheesy as
it's, _this=this; setTimeout('ale rt(_this);',100 0);
or such

I have tried assigning it to a variable (like I said) and I always get "variable is not
defined."

use

setTimeout(func tion(){alert(th is)},1000)

Mar 23 '07 #5
On Mar 23, 4:00 pm, "-Lost" <missed-s...@comcast.ne twrote:
I am calling setTimeout within the context of an object, and whilst this exists, it
refuses to be passed along to the function I call. For example:

$elemById('id') .change = function()
{
// the function returns the object itself, 'this' exists
alert(this); // [object HTMLSelectEleme nt]
setTimeout('ale rt(this);',1000 ); // [object Window]
}
The string passed to setTimeout is essentially eval'd as global code
when the time is up, at that point you have an anonymous function
whose this keyword references the window object.

If you want to get the original function's this, you need to set a
local variable and create a closure back to it:

$elemById('id') .change = function() {
alert(this);
var that = this;
setTimeout(func tion(){alert(th at)}, 1000);
}

>
So, obviously there is something going on that I have not yet learned to deal with.
First, I went with assigning the object (this) to a variable.
You didn't do that, you passed the string 'this' to be eval'd when the
setTimeout runs.
[...]
>
So, what am I missing?
Read the following Richard Cornford article on closures, it covers
quite a bit on function instantiation that is relevant here:

<URL: http://www.jibbering.com/faq/faq_notes/closures.html >

Ignore pretty much everything else that's been said in this thread.
--
Rob

Mar 23 '07 #6
On Mar 23, 4:21 pm, Danny <dann90...@blue bottle.comwrote :
Yes indeed the 'this' scope does change,
Yes what? Please don't top-post here, reply below trimmed quotes.
But anyway...

No, it doesn't. A function's this keyword is set by the calling
function, that's it.
since 'this' is always the evented
caller, or the caller object to which the event/call occurring defaults to.
No, it's not. It is set by the calling function and can be set to
whatever the calling function wants it to be - read up on call and
apply methods.
[...]
>
You can always use a local var, to keep it within the scope, kinda cheesy as
it's, _this=this; setTimeout('ale rt(_this);',100 0);
Which creates _this as a global variable, not local. Some other
function may change what it references in the meantime. If you use:

var _this = this;
setTimeout('ale rt(_this);',100 0);

it still won't work because you are passing a string to setTimeout, it
can't reference the local _this. What I think you meant to use is:

var _this = this;
setTimeout(func tion(){alert(_t his);}, 1000);
--
Rob

Mar 23 '07 #7
"RobG" <rg***@iinet.ne t.auwrote in message
news:11******** **************@ y66g2000hsf.goo glegroups.com.. .
On Mar 23, 4:00 pm, "-Lost" <missed-s...@comcast.ne twrote:
>I am calling setTimeout within the context of an object, and whilst this exists, it
refuses to be passed along to the function I call. For example:

$elemById('id' ).change = function()
{
// the function returns the object itself, 'this' exists
alert(this); // [object HTMLSelectEleme nt]
setTimeout('ale rt(this);',1000 ); // [object Window]
}

The string passed to setTimeout is essentially eval'd as global code
when the time is up, at that point you have an anonymous function
whose this keyword references the window object.
OK, now *that* really made sense.
If you want to get the original function's this, you need to set a
local variable and create a closure back to it:

$elemById('id') .change = function() {
alert(this);
var that = this;
setTimeout(func tion(){alert(th at)}, 1000);
}

>>
So, obviously there is something going on that I have not yet learned to deal with.
First, I went with assigning the object (this) to a variable.

You didn't do that, you passed the string 'this' to be eval'd when the
setTimeout runs.
[...]
>>
So, what am I missing?

Read the following Richard Cornford article on closures, it covers
quite a bit on function instantiation that is relevant here:

<URL: http://www.jibbering.com/faq/faq_notes/closures.html >

Ignore pretty much everything else that's been said in this thread.
Thanks, Rob. I will definitely read that article again!

Thanks for all the clarification as well.

-Lost
Mar 24 '07 #8

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

Similar topics

3
14952
by: domeceo | last post by:
can anyone tell me why I cannot pass values in a setTimeout function whenever I use this function it says "menu is undefined" after th alert. function imgOff(menu, num) { if (document.images) { document.images.src = eval("mt" +menu+ ".src") } alert("imgOff_hidemenu"); hideMenu=setTimeout('Hide(menu,num)',500);
29
8781
by: Mic | last post by:
Goal: delay execution of form submit Code (Javascript + JScript ASP): <% Response.Write("<OBJECT ID='IntraLaunch' STYLE='display : none' WIDTH=0 HEIGHT=0 CLASSID='CLSID:0AE533FE-B805-4FD6-8AE1-A619FBEE7A23' CODEBASE='IntraLaunch.CAB#version=5,0,0,3'>") Response.Write("<PARAM NAME='ImageLoc' VALUE='Null'>") Response.Write("<PARAM NAME='ImageSrc' VALUE='Null'>")
7
1646
by: Antony Sequeira | last post by:
Hi While looking at some code I realized that the built in setTimeout function takes a string that is later evaluated in the original caller's context. How does one achieve something similar in user defined functions. -Antony
2
4672
by: Athanasius | last post by:
Could someone shed some light as to why the following setTimeout function will not work on the Mac IE5.2? It does however work on PC(Forefox,Netscape,IE) & Mac(Safari,Firefox). Here is the script, it should simply present an alert message after 5 seconds. Thanks. <html> <head> <script language="javascript"> function MsgTimer() { var self = this;
8
15103
by: VA | last post by:
Suppose I have setTimeout(foo(),n); long_running_function(); Would foo() be executed even when long_running_function() is still executing? In other words, does the setTimeout() pre-empt anything else?
12
5556
by: Andrew Poulos | last post by:
With the following code I can't understand why this.num keeps incrementing each time I create a new instance of Foo. For each instance I'm expecting this.num to alert as 1 but keeps incrementing. Foo = function(type) { this.num = 0; this.type = type this.trigger(); } Foo.prototype.trigger = function() {
2
10412
by: rain_c1 | last post by:
hi, i think this is a little exercise for real experts, but i suffer from real headaches because of it... :-\ i have an object method (method1), that calls setTimeout with an other method (method2) as parameter which calls further another method (method3), but i do not know how to realize it. it is important to use object context and not static members, because method3 uses a member (more precisely a constructor parameter) that
15
3796
by: nikki_herring | last post by:
I am using setTimeout( ) to continuously call a function that randomly rotates/displays 2 images on a page. The part I need help with is the second image should rotate 3 seconds after the first image rotates. I cannot figure out how to accomplish the 3 second delay. My code is pasted below: function randPic(){ randPic1(); randPic2();
19
1847
by: liketofindoutwhy | last post by:
I did some animation using var oDiv = {}; oDiv.x = 100; oDiv.y = 100; oDiv.node = document.getElementById('divImage'); oDiv.node.style.position = "absolute"; oDiv.doAnimation = function() {
0
9645
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
9481
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
10336
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
10155
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
10095
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
9953
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
7502
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
6741
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
5383
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...

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.