Path: csiph.com!aioe.org!news.mb-net.net!open-news-network.org!.POSTED.69.235.197.178.dynamic.wless.lssmb00p-cgnat.res.cust.swisscom.ch!not-for-mail From: Thomas 'PointedEars' Lahn Newsgroups: comp.lang.javascript Subject: Re: Reference var in (function(){})() Date: Tue, 01 Aug 2017 12:40:28 +0200 Organization: PointedEars Software (PES) Lines: 82 Message-ID: <3122783.iIbC2pHGDl@PointedEars.de> References: Reply-To: Thomas 'PointedEars' Lahn Mime-Version: 1.0 Content-Type: text/plain; charset="UTF-8" Content-Transfer-Encoding: 8Bit Injection-Info: gwaiyur.mb-net.net; posting-host="69.235.197.178.dynamic.wless.lssmb00p-cgnat.res.cust.swisscom.ch:178.197.235.69"; logging-data="12806"; mail-complaints-to="abuse@open-news-network.org" User-Agent: KNode/4.14.2 X-Face: %i>XG-yXR'\"2P/C_aO%~;2o~?g0pPKmbOw^=NT`tprDEf++D.m7"}HW6.#=U:?2GGctkL,f89@H46O$ASoW&?s}.k+&. There's some code that looks like > > var con = (function() { > var opt0 = {}, > opt1 = {}, > opt2 = {}, > opt3 = {}, > ... Who is doing such nonsense? > function x() { > // > } > })() > > Within the function x I need to reference each of the (many) "opt" > objects. Objects have identity, not name. > I'd like to reference them in a for loop e.g. > > for (i = 0; i < len; i++) { > eval("opt" + i) = ... > } > > but how can I do it without using eval? You cannot. Therefore, use an Array instance – var con = (function () { var opt = [ {}, {}, {}, {} // , ... ]; function x () { for (var i = 0, len = opt.length; i < len; ++i) { // opt[i] = ... } } // x(…) })(); – or an Object instance – var con = (function () { /* “opt” then refers to an object that does not inherit properties */ var opt = Object.assign(Object.create(null), { 0: {}, 1: {}, 2: {}, 3: {} // , ... }); function x () { for (var i = 0; i < len; ++i) { // opt[i] = ... } } // x(…) })(); – instead. -- PointedEars FAQ: | | Twitter: @PointedEars2 | Please do not cc me./Bitte keine Kopien per E-Mail.