View Full Version : settimeout scope ?

02-20-2007, 06:14 PM
mainly interested in how to make "/*1.*/" to work. Thanks for help.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html class = "html">
<head class = "head">
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Untitled Document</title>
<script language="javascript" type="text/javascript">
function MyObj()
this.doIt = function()
/*0.*/ test2('b'); //works
/*1.*/ var t=setTimeout("test2('a')",1000); //does not
/*2.*/ var t=setTimeout("this.test('a')",1000); //does not
/*3.*/ var t=setTimeout("myObj.test('a')",1000); //works

this.test = function(param)

function test2(param)

<!--end of need this package for css event selectors-->
<body style = 'height:100%' onload="myObj = new MyObj();" >
<button value="fdjgsda" onclick="myObj.doIt();"> </button>

02-21-2007, 01:30 PM
setTimeout, if given a string argument, compiles that string into the body of a function in the global scope. However, using a string argument is discouraged, so don't do that.

setTimeout can take a function object as it's first argument instead of a string. This function will be called from the global scope, but because JavaScript has closures, the body of the function will keep the local scope in which it was declared. Thus

/* 1. */var t=setTimeout(function(){test2('a')},1000);
/* 2. alt 1. */var me=this,t=setTimeout(function(){me.test('a')},1000);
/* 2. alt 2. */var t=setTimeout((function(me){return function(){me.test('a')}})(this),1000);

02-22-2007, 11:58 PM
Thanks. Solved my problem.