Path: csiph.com!v102.xanadu-bbs.net!xanadu-bbs.net!us.feeder.erje.net!feeder.erje.net!eu.feeder.erje.net!news.mb-net.net!open-news-network.org!aioe.org!.POSTED!not-for-mail From: Cezary Tomczyk Newsgroups: comp.lang.javascript Subject: Re: Two versions of code - advantages and differences Date: Sun, 06 Jan 2013 21:38:04 +0100 Organization: Aioe.org NNTP Server Lines: 56 Message-ID: References: NNTP-Posting-Host: RMrsF+s1qSnxq5Qkkqjnpw.user.speranza.aioe.org Mime-Version: 1.0 Content-Type: text/plain; charset=UTF-8; format=flowed Content-Transfer-Encoding: 7bit X-Complaints-To: abuse@aioe.org User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:17.0) Gecko/17.0 Thunderbird/17.0 X-Notice: Filtered by postfilter v. 0.8.2 Xref: csiph.com comp.lang.javascript:17987 W dniu 2013-01-05 21:54, Luc Yen pisze: [...] > The usage is quite different, for version 1: > var test = fn(); // return the current 'el' value or something else > Since 'el' can be changed anytime in its execute context, the result is unpredictable. We can also assuming that el will never be changed. > For version 2, you must first create a variable to hold the returned function if 'el' is defined. > var fnGetTestEl = fn(); // (1) > At this point, the 'el' is fixed and can't be accessed outside it's context. Later, you use: > var elTest = fnGetTestEl(); > Every time you invoke this function, the result is predictable. (if that id="test" element is still there) That's true. > The difference is version 2 must eventually return a *callable* expression in that fallback part. > It could be: > > if (el) { > return function() { return el; }; > } else { > // fallback process > return function() { return null; }; // simply state that we can't find el at first place > } > > Or something like: > > if (el) { > return function() { return el; }; > } else { > // el = document.createElement('div'); > // el.id = 'test'; > // maybe inject el into the document here > return function() { return el; }; // now el is properly defined > } This is true according to fallback, but I was thinking about memory management and efficient. After study more closely http://jibbering.com/faq/notes/closures/ seems that: var fn = (function(){ var t = 'test'; return function(){ return t; }; }()); closure is executed only once and return reference to anonymous function, but, as I understand, closure can not be dispose by garbage collector due to stored reference of t inside returned anonymous function. If I understand it correctly. -- Cezary Tomczyk http://www.ctomczyk.pl/