Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.javascript > #22870

setTimeout() (was: I thought I understood JavaScript till they asked me this on a job interview)

Path csiph.com!usenet.pasdenom.info!weretis.net!feeder4.news.weretis.net!news.teledata-fn.de!newsfeed.arcor.de!newsspool3.arcor-online.net!news.arcor.de.POSTED!not-for-mail
Content-Type text/plain; charset="UTF-8"
Message-ID <5802771.9clCDhIZfi@PointedEars.de> (permalink)
From Thomas 'PointedEars' Lahn <PointedEars@web.de>
Reply-To Thomas 'PointedEars' Lahn <cljs@PointedEars.de>
Organization PointedEars Software (PES)
Date Wed, 29 Jan 2014 12:59:03 +0100
User-Agent KNode/4.11.3
Content-Transfer-Encoding 8Bit
X-Face %i>XG-yXR'\"2P/C_aO%~;2o~?g0pPKmbOw^=NT`tprDEf++D.m7"}HW6.#=U:?2GGctkL,f89@H46O$ASoW&?s}.k+&.<b';Md8`dH6iqhT)6C^.Px|[=M@7=Ik[_w<%n1Up"LPQNu2m8|L!/3iby{-]A+#YE}Kl{Cw$\U!kD%K}\2jz"QQP6Uqr],./"?;=4v
Face iVBORw0KGgoAAAANSUhEUgAAADAAAAAwBAMAAAClLOS0AAAAGFBMVEXTxa4RFk5dUWANED8PFEfy7+MGBiW+n3ZNF/QuAAACaElEQVQ4jVXUwVOcMBQG8Dc7Rc4PUntdWV2uxjDpGaGeozOp1woar4jd5t/v9wLstMwsA/ntlxdCAgUc1hjTc9/JCZfGoo3wG3HdmdAWrIJRHe7GM/TmpY5VFefuVcAkkPbLIaN8rmPmjloyZxgyR3GuJ4K0AGtJ2htz8o7yqikm759fldQXaMpbDzjKAG+8v+AugVTOPO5DOjLvGtUYQwh0CPjnVMyGd+8/GfUB5nLKJDD2aLDh5HYyMDJGDwQIo2ZmZcKbowNmAdB/AzyFhrmF2MHRb0QJJfaAnwGB6orZhoykLzJtGwF/xpYxI1dswomiUj3gTuAIqCn/4C7cULwGNBtwMTk3Y4LfKB5YUaOKBKYtpplm7u0vip8tU1NWWyI/7XdcSuIDoMt6rVHMWT0DbjHPGqDqZVSa6zleLcUTcIKLoMv3ueJluALtAo9B302zPPlrtiVScRdCjXvVh3e3JpYa/jjkuC9N+LrBMlz/eAN4eQijX2EdLo6c5tGGHwLyHFtXk89dDGHwCVhG9T0S/j55AhRZgkMCmUQXJ49TnS1wnQDvw0eAh9ICeMmEFbCnPMFzjAvsWoEWEFdYEx+S0MoUZ1gT1wId8+AF3Bl2OoEu906AUHx5VLw/gXYg/x84loOah/2UYNrgiwSwGO7RfUzVBbx/kgpckumGOi6QirtD6gkLTitbnxNol47S2jVc2vsN5kPqaAHT8uUdAJM4v/DanjYOwmUjWznGfwB7sGtAtor5BgofDuzaRj4kSQAqDakTsKORa3Q3xKi3gE1fhl71KRMqrdZ2AWNNg/YOhQyrVBnb+i+nEg4bsDA+egAAAABJRU5ErkJggg==
Subject setTimeout() (was: I thought I understood JavaScript till they asked me this on a job interview)
Newsgroups comp.lang.javascript
References <b3e79681-ee2f-45bb-bcac-39505315bfde@googlegroups.com> <7998487.AcjmSas2GF@PointedEars.de> <4db39251-6142-4a8d-a6f4-027a93fef383@googlegroups.com>
MIME-Version 1.0
Lines 127
NNTP-Posting-Date 29 Jan 2014 12:59:30 CET
NNTP-Posting-Host 77b822c6.newsspool2.arcor-online.net
X-Trace DXC=bEf0\4;obST@>[RYkFXOIPA9EHlD;3YcR4Fo<]lROoRQ8kF<OcfhCO[ohhV8iXDLQTDZm8W4\YJN\YUVHKH;GI^WA:4gUTI10KQNfO^0ZjhNIQ
X-Complaints-To usenet-abuse@arcor.de
Xref csiph.com comp.lang.javascript:22870

Show key headers only | View raw


Alon Melanker wrote:

[Fixed quotation]

> Thomas 'PointedEars' Lahn wrote:
>> Alon Melanker wrote:
>> >   function damn() {
>> >       this.x = 4;
>> >       var y = 3;
>> >
>> >       setTimeout(function() {alert(this.x); alert(y)}, 100);
>> >       
>> >        this.aa = function() {
>> >         alert(this.x);
>> >       };
>> >   }
>> >   
>> >   aaa = new damn();
>> >   aaa.aa();
>> > 
>> > What would be the output?!
>> > 
>> > The correct answer should be 4 undefined and 3.
>> > […]
>> > The question is why this.x inside setTimeout does not alert 4?
>> 
>> I could tell you (and probably others will, with wrong explanations
>> in-between), but try debugging first.  You will learn more for your next
>> interview this way.
>> 
>> <http://devtoolsecrets.com/>
>> <http://PointedEars.de/faq#posting>
>> […]
> 
> Thanks, this help me understand that the problem, apparently when this
> function() {alert(this.x+'a'); alert(y+'b')} is invoked it is not invoked
> as an object method which leads that this refers to window object.

Almost :)  It depends on the (DOM) implementation, and you should not rely 
on that “this” refers to a Window instance.

If the function is not called as a method, then the “this” value is set to 
the Global Object in non-strict mode, and to “undefined” in strict mode, 
when control enters the function execution context.

If the function is called as a method of the object referred to by the 
“window” property of the Global Object, or a Window instance, the “this” 
value is set to a reference to it.

It is not easy to tell the two objects apart because they are either 
inheriting from each other or are part of the same scope chain.  (Therefore, 
some people have the misconception that they are the same object.)  However, 
using ECMAScript Edition 5.x strict mode, i.e. in a more recent browser, you 
can do it with the following code:

  /* window.alert() instead of console.log() should also work */
  setTimeout(function () { "use strict"; console.log(this); }, 100);

The difference is this: In strict mode, if the function is not called as a 
method, the “this” value is set to “undefined”.  If instead it is called as 
a method, the “this” value is set to the object it is called as a method of. 
[1]

My results show that in Chromium 31 for GNU/Linux the function is called as 
a method of a Window instance.  This is unsurprising because setTimeout() 
really is a method of Window instances, not of the Global Object (it is a 
*host* object’s method, not a native one’s; it is _not_ part of the 
programming language, but of the capabilities of the host environment), and 
thus should be written

  window.setTimeout(…);

Likewise for alert(…).

The other two possibilities I mentioned are that a SyntaxError or TypeError 
exception could be thrown.  There is a third possibility, a ReferenceError 
exception.

A SyntaxError exception will be thrown (or something to the same effect will 
happen) if anonymous function expressions are not supported.  This is 
possible, but increasingly unlikely these days.  Anonymous function 
expressions were introduced with

  - Netscape JavaScript 1.2 in Navigator 4.04¹;
  - Microsoft JScript 5.5.6330 in Internet Explorer 5.5 or earlier;
  - Opera ECMAScript 7.02 in Opera 7.02 or earlier;
  - KDE JavaScript 4.6.5 or earlier;
  - Apple JavaScriptCore 531.22.7 in Safari 4.05 or earlier, and
  - Google V8 3.7.12.12 in Chrome 17.0.963.78 and earlier.

A TypeError exception will be thrown if “setTimeout” or “alert” do not refer 
to a callable object.  This can likely be prevented if a feature test 
determines that their values are likely callable before they are called.

A ReferenceError exception will be thrown if setTimeout() or alert() are not 
properties of an object in the scope chain.  That is, either there are no 
such methods (unsuitable host environment), or the object that they are 
methods of is not in the scope chain of the execution context of the 
/CallExpression/s.  This also shows that it is safer to use 
window.setTimeout() and window.alert(), respectively.

See jsx.object.isHostMethod() [3] for a solution regarding the latter two 
possibilities.


Please trim your quotations to the relevant parts next time, as explained in 
the FAQ referred above.  And avoid Google Groups; among other bugs, it has 
inserted interleaving empty lines in your posting.

___________
¹ The ECMAScript Support Matrix 2 [2] is saying “JavaScript 1.5” because
  the testing framework is not yet compatible with JavaScript versions
  before 1.5.

[1] ECMAScript Language Specification, Edition 5.1, sections 11.2.3,
    13.2.1, and 10.4.3.
    <http://ecma-international.org/ecma-262/5.1/#sec-11.2.3>
    <http://ecma-international.org/ecma-262/5.1/#sec-13.2.1>
    <http://ecma-international.org/ecma-262/5.1/#sec-10.4.3>
[2] <http://PointedEars.de/es-matrix>
[3] <http://PointedEars.de/wsvn/JSX/branches/live/object.js>
    <http://PointedEars.de/wsvn/JSX/trunk/object.js>
-- 
PointedEars

Twitter: @PointedEars2
Please do not Cc: me. / Bitte keine Kopien per E-Mail.

Back to comp.lang.javascript | Previous | Next — Previous in thread | Next in thread | Find similar | Unroll thread


Thread

I thought I understood JavaScript till they asked me this on a job interview Alon Melanker <melankeril@gmail.com> - 2014-01-28 05:57 -0800
  Re: I thought I understood JavaScript till they asked me this on a job interview Thomas 'PointedEars' Lahn <PointedEars@web.de> - 2014-01-28 15:58 +0100
    Re: I thought I understood JavaScript till they asked me this on a job interview Hans-Georg Michna <hans-georgNoEmailPlease@michna.com> - 2014-01-28 16:38 +0100
      Re: I thought I understood JavaScript till they asked me this on a job interview "Evertjan." <exxjxw.hannivoort@inter.nl.net> - 2014-01-28 17:25 +0100
      Re: I thought I understood JavaScript till they asked me this on a job interview Christoph Michael Becker <cmbecker69@arcor.de> - 2014-01-28 19:00 +0100
        Re: I thought I understood JavaScript till they asked me this on a job interview Hans-Georg Michna <hans-georgNoEmailPlease@michna.com> - 2014-01-29 10:22 +0100
          Re: I thought I understood JavaScript till they asked me this on a job interview Christoph Michael Becker <cmbecker69@arcor.de> - 2014-01-29 17:34 +0100
            Re: I thought I understood JavaScript till they asked me this on a job interview Jim T. <x@y.z> - 2014-01-29 12:45 -0500
            Re: I thought I understood JavaScript till they asked me this on a job interview Hans-Georg Michna <hans-georgNoEmailPlease@michna.com> - 2014-01-30 09:09 +0100
    Re: I thought I understood JavaScript till they asked me this on a job interview Alon Melanker <melankeril@gmail.com> - 2014-01-29 01:52 -0800
      setTimeout() (was: I thought I understood JavaScript till they asked me this on a job interview) Thomas 'PointedEars' Lahn <PointedEars@web.de> - 2014-01-29 12:59 +0100
  Re: I thought I understood JavaScript till they asked me this on a job interview Bjoern Hoehrmann <bjoern@hoehrmann.de> - 2014-01-29 14:30 +0100
    Re: I thought I understood JavaScript till they asked me this on a job interview Thomas 'PointedEars' Lahn <PointedEars@web.de> - 2014-01-29 15:39 +0100

csiph-web