Why is using the JavaScript eval function a bad idea?
Asked Answered
V

25

586

The eval function is a powerful and easy way to dynamically generate code, so what are the caveats?

Vitrescence answered 17/9, 2008 at 19:9 Comment(7)
Don't be eval() by Simon Willison - 24ways.org/2005/dont-be-evalVitrescence
As outlined in moduscreate.com/javascript-performance-tips-tricks - (new Function(str))() is more performant than eval(str). Just my 2 cents :)Condottiere
apparently new fcuntion(a) is 67% slower than eval(a) on chromeOtocyst
for me new functions(a) is 80% slower latest chrome on osxKallman
I added a static function, just to compare the performance. jsperf.com/eval-vs-new-function/2Antipater
same caveats as include and require in PHP. eval may as well be called "include_from_string" or "runtime_compile". Not only is it not evil, but I am certain it is one of the fundamental reasons why scripting was created - it's much easier to make a script that evals' to an object and start using it/change it without recompiling than recompiling a DLL every time you need a change. From a high level viewpoint, Eval is the same as compiling a c file to a DLL, then calling its' entry point, and linking to its' state symbol(or have the entry point return the state object).Gnni
@Antipater Your site's downLavern
N
415
  1. Improper use of eval opens up your code for injection attacks

  2. Debugging can be more challenging (no line numbers, etc.)

  3. eval'd code executes slower (no opportunity to compile/cache eval'd code)

Edit: As @Jeff Walden points out in comments, #3 is less true today than it was in 2008. However, while some caching of compiled scripts may happen this will only be limited to scripts that are eval'd repeated with no modification. A more likely scenario is that you are eval'ing scripts that have undergone slight modification each time and as such could not be cached. Let's just say that SOME eval'd code executes more slowly.

Neocolonialism answered 17/9, 2008 at 19:17 Comment(21)
@JeffWalden, great comment. I've updated my post although I realize it has been a year since you posted. Xnzo72, if you had qualified your comment somewhat (as Jeff did) then I might be able to agree with you. Jeff pointed out the key: "eval of the same string multiple times can avoid parse overhead". As it is, you are just wrong; #3 holds true for many scenarios.Neocolonialism
@Prestaul: Since the supposed attacker can just use whatever developer tool to change the JavaScript in the client, why do you say Eval() opens up your code to injection attacks? Isn't already opened? (I'm talking about client JavaScript of course)Understate
@EduardoMolteni, we don't care (and indeed cannot prevent) users from executing js in their own browsers. The attacks we are trying to avoid are when user provided values get saved, then later placed into javascript and eval'd. For example, I might set my username to: badHackerGuy'); doMaliciousThings(); and if you take my username, concat it into some script and eval it in other people's browsers then I can run any javascript I want on their machines (e.g. force them to +1 my posts, post their data to my server, etc.)Neocolonialism
AFAIK, google-chrome & chromium dev tools makes debugging eval'ed code just like debugging other js files. but you cannot put breakpoints though.Maricela
In general, #1 is true for quite a lot, if not most function calls. eval() shouldn't be singled out and avoided by experienced programmers, just because inexperienced programmers abuse it. However, experienced programmers often have a better architecture in their code, and eval() will rarely be required or even thought about due to this better architecture.Liberalize
@frodeborli, I disagree with your opening statement. eval is fundamentally different from a function call. Read my comment to EduardoMolteni (2 above yours) for an explanation. Injection attacks specifically refer to taking user input and allowing it to execute somewhere other than their own browser. (e.g. the server or another user's browser) I do, however, agree that eval is rarely required if you architect your applications well. It should be avoided because there is almost always a better and more secure solution.Neocolonialism
@TamilVendhan Sure you can put breakpoints. You can access the virtual file created by Chrome for your evaled coded by adding the debugger; statement to your source code. This will stop the execution of your program on that line. Then after that you can add debug breakpoints like it was just another JS file.Edelmiraedelson
Thank you. This concise answer just told be exactly my I can use eval in my current task/context. There is so much unclear advice to just not use it.Finnie
@Liberalize Your second statement is also wrong. Many experienced programmers / frameworks still use evil() a lot. Take a look at SAP OpenUI5 for example.Papyrus
@Finnie Think well before using eval()! There are more strict CSP out there preventing you from using eval(). Take Firefox OS for example.Papyrus
@AndreFiedler Neither of my statements are wrong. You might disagree, if you wish. Any functionality can be implemented in any Turing complete language. Only a few languages have eval, thus eval is never NEEDED - it is just a convenience. Whether or not eval is a function call or a language construct is a completely different question.Liberalize
@Liberalize yeah, it's never NEEDED, but my statement was about experienced programmers often have a better architecture in their code. Not so often as you thought. ;)Papyrus
@AndreFiedler Experienced programmers may have poor code. That we can agree on. :) But a group of experienced programmers usually have a better architecture than they used to have when they were inexperienced, is what I meant to say.Liberalize
webpack will argue with you :)Communism
eval isn't all that bad. I use it in my Epic Random String Generator and it works great!Aruspex
If you're executing different code each time, compiling and caching would have no benefit, regardless of whether that you're using eval or not.Dildo
(1) how is this any different from require/include? If you need to include foreign code/user code why is this even an issue? (2) modern javascript engines can tell you the exact line and offset of errors inside evaluated code as if you ran that code from anonymousScope.js. (3) how is this any different from any kind of compilation process? i'd argue that conditionally generating a function with eval is often faster than writing a function with conditions in it, or using global variables(eg manual inlining), when those generated functions are called many times.Gnni
@Dmitry, I'll just address 1 & 2: The big difference is that, if you are using eval, you are programmatically generating code and the most common reason people do this is to inject user-supplied information (or code) into code. This is fundamentally unsafe as it needlessly opens your code up to injection attacks. If you are using code generation for optimizations then maybe there is a legitimate use, but this is certainly a minority use case.Neocolonialism
most common use of eval is to implement "require" functionality without inventing a new parser. Also I'm not sure you know what injection attacks are, but on the client side you can't avoid injection other than by function locals, and iife locals can't be touched by anything but a memory editor. On the server side, you need to be careful who you let execute arbitrary code, but even there its still used for implementing require and as a shell alternative.Gnni
@Dmitry, I think you fundamentally misunderstand injection attacks... There is no threat from injection done on the client side by a user viewing their own content. We're concerned about XSS which has to do with injection of malicious content from ANOTHER user, giving them access to a page in which a different user is logged in. There are ways to avoid this but if you use eval it depends entirely on the knowledge and diligence of the developers. If you want require, just use a lib that does it right. See: codereview.stackexchange.com/questions/25901/…Neocolonialism
@Neocolonialism eval in xss is dangerous but can be mitigated by hiding important data in local variables inside functions, and credential testing before eval of text loaded from foreign domains. eg instead of eval of code you could json parse the request to eval and check the objects credentials before eval of its code property. that said, i can't imagine a need to eval of xss.Gnni
M
353

eval isn't always evil. There are times where it's perfectly appropriate.

However, eval is currently and historically massively over-used by people who don't know what they're doing. That includes people writing JavaScript tutorials, unfortunately, and in some cases this can indeed have security consequences - or, more often, simple bugs. So the more we can do to throw a question mark over eval, the better. Any time you use eval you need to sanity-check what you're doing, because chances are you could be doing it a better, safer, cleaner way.

To give an all-too-typical example, to set the colour of an element with an id stored in the variable 'potato':

eval('document.' + potato + '.style.color = "red"');

If the authors of the kind of code above had a clue about the basics of how JavaScript objects work, they'd have realised that square brackets can be used instead of literal dot-names, obviating the need for eval:

document[potato].style.color = 'red';

...which is much easier to read as well as less potentially buggy.

(But then, someone who /really/ knew what they were doing would say:

document.getElementById(potato).style.color = 'red';

which is more reliable than the dodgy old trick of accessing DOM elements straight out of the document object.)

Multitude answered 17/9, 2008 at 20:27 Comment(8)
Hmm, guess I got lucky when I was first learning JavaScript. I always used "document.getElementById" to access the DOM; ironically, I only did it at the time because I didn't have a clue how objects worked in JavaScript ;-)Liverpudlian
agree. Sometimes eval is ok e.g. for JSON responses from webservicesTripitaka
@schoetbi: Shouldn't you use JSON.parse() instead of eval() for JSON?Burse
@Nyuszika7H: when you can, sure. There are still a fair few extant browsers that don't have it, alas.Multitude
@Multitude code.google.com/p/json-sans-eval works on all browsers, so does github.com/douglascrockford/JSON-js . Doug Crockford's json2.js does use eval internally, but with checks. Besides, it's forward-compatible with built-in browser support for JSON.Amatory
Sure, you can use libraries if you like. But all browsers are going to have to download the library code, even if they have native support so will never use it. For cases where I'm sure the JSON is going to be safe, and valid as a JS literal as well as JSON, I'd much rather save the extra bulk and plump for eval.Multitude
@Multitude There is something called feature-detection and polyfills to handle missing JSON libraries and other things (look at modernizr.com)Perspiratory
"eval isn't always evil." Isn't it? I don't know of any case where eval is the best option. FWIW you can achieve much of the same functionality using the Function constructor ( developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… ), which is slightly less evil.Operon
J
38

I believe it's because it can execute any JavaScript function from a string. Using it makes it easier for people to inject rogue code into the application.

Jacintajacinth answered 17/9, 2008 at 19:11 Comment(11)
What is the alternative then?Vally
Really the alternative is just write code that doesn't require it. Crockford goes into length about this, and if you need to use it, he pretty much says that its a program design flaw and needs to be reworked. In truth, I agree with him too. JS for all it's flaws is really flexible, and allows a lot of room to make it flexible.Jacintajacinth
but when you get a response from the server by AJAX, you will get response text xmlHttp.responseText, and you will need to use eval to execute it.Vally
Not true, most frameworks have a method to parse JSON, and if you aren't using a framework, you can use JSON.parse (). Most browsers support it, and if you're really in a pinch, you could write a parser for JSON pretty easily.Jacintajacinth
I don't buy this argument, because it already is easy to inject rogue code into a Javascript application. We have browser consoles, script extensions, etc... Every single piece of code sent to the client is optional for the client to execute.Sundew
The point is that's it's easier for me to inject code into your browser. Let's say you're using eval on a query string. If I trick you into clicking a link that goes to that site with my query string attached, I've now executed my code on your machine with full permission from the browser. I want to key log everything you type on that site and send it to me? Done and no way to stop me because when eval executes, the browser gives it highest authority.Jacintajacinth
I use it for dynamic formula processing where the formula is sent from a server. There is no security risk here and the only alternative would be to write a big JavaScript function to deconstruct the formulas.Sampan
@Dildo Then how do you feature-detect for ECMAScript 6 (ES6) support without eval? Or does Crockford recommend just shunning ES6 entirely?Bury
@Sampan Then serve the big function as a separate .js file and include it by appending a script element to the document.Bury
@DamianYerrick It's impossible in some feature detection to not use it. At that point I would question if ES6 was really worth implementing in that scenario. If you have to do feature detection to see if you can use it, that means you have to account for the scenarios where you can't. This really means that you have to write your code twice (once in ES5 and once in ES6). I'd just stay with ES5, or write the code in TypeScript etc so I can transpile to ES6 when I don't have to support 5 anymore.Jacintajacinth
Why would anyone eval a query string? Nowadays you don't even need to POST, let alone GET, because there are websockets. And you can always sandbox an iframe, or use a web worker, where there are only 'messages' communicated between the two and have no acess to each other's namespace.Sympathize
S
29

It's generally only an issue if you're passing eval user input.

Somnambulism answered 17/9, 2008 at 19:12 Comment(1)
This means just some simple on page calculations will not harm anything. Good to know that.Ascend
A
28

Two points come to mind:

  1. Security (but as long as you generate the string to be evaluated yourself, this might be a non-issue)

  2. Performance: until the code to be executed is unknown, it cannot be optimized. (about javascript and performance, certainly Steve Yegge's presentation)

Alphorn answered 17/9, 2008 at 19:20 Comment(2)
Why security is an issue if client anyway could do with our code anything he/she wants ? Greasemonkey ?Grindle
@PaulBrewczynski, the security problem appears when user A saves his part of code to be evaluated and then, that little piece of code runs on user's B browserGuttapercha
O
22

Passing user input to eval() is a security risk, but also each invocation of eval() creates a new instance of the JavaScript interpreter. This can be a resource hog.

Orientation answered 17/9, 2008 at 19:28 Comment(1)
In the 3+ years since I answered this, my understanding of what happens has, let's say, deepened. What actually happens is a new execution context is created. See dmitrysoshnikov.com/ecmascript/chapter-1-execution-contextsOrientation
A
15

Mainly, it's a lot harder to maintain and debug. It's like a goto. You can use it, but it makes it harder to find problems and harder on the people who may need to make changes later.

Alchemist answered 17/9, 2008 at 19:12 Comment(2)
Eval can be used to substitute missing metaprogramming features, like templates. I like compact generator way more than endless list of functions upon functions.Bein
As long as the string doesn't come from the user, or is limited to the browser you can. JavaScript has lots of metaprogramming power using stuff like changing prototypes, obj[member], Proxy, json.parse, window, decorator functions(adverbs) where newf = decorator(oldf), higher order function like Array.prototype.map(f), passing arguments to other functions, keyword arguments via {}. Can you tell me a use case where you can't do these instead of eval?Passus
O
14

One thing to keep in mind is that you can often use eval() to execute code in an otherwise restricted environment - social networking sites that block specific JavaScript functions can sometimes be fooled by breaking them up in an eval block -

eval('al' + 'er' + 't(\'' + 'hi there!' + '\')');

So if you're looking to run some JavaScript code where it might not otherwise be allowed (Myspace, I'm looking at you...) then eval() can be a useful trick.

However, for all the reasons mentioned above, you shouldn't use it for your own code, where you have complete control - it's just not necessary, and better-off relegated to the 'tricky JavaScript hacks' shelf.

Onshore answered 17/9, 2008 at 21:23 Comment(3)
Just updating the above code.. --hi there!-- needs to be in quotes as it is a string. eval('al' + 'er' + 't(' + '"hi there!"' + ')');Wholly
[]["con"+"struc"+"tor"]["con"+"struc"+"tor"]('al' + 'er' + 't(\'' + 'hi there!' + '\')')()Vary
Yikes, there were social networking sites that restricted alert() but allowed eval()?!Slavophile
M
13

Unless you let eval() a dynamic content (through cgi or input), it is as safe and solid as all other JavaScript in your page.

Mombasa answered 17/9, 2008 at 19:24 Comment(3)
While this is true -- if your content isn't dynamic, what reason is there to use eval for it at all? You could just put the code in a function and call it, instead!Duchess
Just for example - to parse returning value (JSON like, server defined strings, etc.) that came from Ajax call.Mombasa
Oh, I see. I would call those dynamic because the client doesn't know ahead of time what they are, but I see what you mean now.Duchess
I
8

Along with the rest of the answers, I don't think eval statements can have advanced minimization.

Industry answered 3/1, 2012 at 3:52 Comment(0)
G
6

It is a possible security risk, it has a different scope of execution, and is quite inefficient, as it creates an entirely new scripting environment for the execution of the code. See here for some more info: eval.

It is quite useful, though, and used with moderation can add a lot of good functionality.

Gonsalves answered 17/9, 2008 at 19:37 Comment(0)
G
5

Unless you are 100% sure that the code being evaluated is from a trusted source (usually your own application) then it's a surefire way of exposing your system to a cross-site scripting attack.

Griffis answered 17/9, 2008 at 19:13 Comment(1)
Only if your server-side security sucks. Client-side security is straight nonsense.Vedanta
S
5

It's not necessarily that bad provided you know what context you're using it in.

If your application is using eval() to create an object from some JSON which has come back from an XMLHttpRequest to your own site, created by your trusted server-side code, it's probably not a problem.

Untrusted client-side JavaScript code can't do that much anyway. Provided the thing you're executing eval() on has come from a reasonable source, you're fine.

Shack answered 17/9, 2008 at 20:10 Comment(4)
Isn't using eval slower than just parsing the JSON?Minion
@Qix - running that test on my browser (Chrome 53) shows eval as somewhat faster than parse.Duchess
@PeriataBreatta Huh, strange. I wonder why. At the time I commented that wasn't the case. However, it's not unheard of for Chrome to get strange performance boosts in certain areas of the runtime from version to version.Late
A little old thread here, but from what I've read-- not claiming I traced it back myself-- JSON.parse in fact eval's it's input in the final stage. So efficiency-wise, takes more work/time. But security-wise, why not just parse? eval is an awesome tool. Use it for things that have no other way. To pass functions through JSON, there is a way to do it without eval. That second parameter in JSON.stringify lets you put a callback to run that you can check via typeof if it's a function. Then get the function's .toString(). There are some good articles on this if you search.Sympathize
C
4

If you spot the use of eval() in your code, remember the mantra “eval() is evil.”

This function takes an arbitrary string and executes it as JavaScript code. When the code in question is known beforehand (not determined at runtime), there’s no reason to use eval(). If the code is dynamically generated at runtime, there’s often a better way to achieve the goal without eval(). For example, just using square bracket notation to access dynamic properties is better and simpler:

// antipattern
var property = "name";
alert(eval("obj." + property));

// preferred
var property = "name";
alert(obj[property]);

Using eval() also has security implications, because you might be executing code (for example coming from the network) that has been tampered with. This is a common antipattern when dealing with a JSON response from an Ajax request. In those cases it’s better to use the browsers’ built-in methods to parse the JSON response to make sure it’s safe and valid. For browsers that don’t support JSON.parse() natively, you can use a library from JSON.org.

It’s also important to remember that passing strings to setInterval(), setTimeout(), and the Function() constructor is, for the most part, similar to using eval() and therefore should be avoided.

Behind the scenes, JavaScript still has to evaluate and execute the string you pass as programming code:

// antipatterns
setTimeout("myFunc()", 1000);
setTimeout("myFunc(1, 2, 3)", 1000);

// preferred
setTimeout(myFunc, 1000);
setTimeout(function () {
myFunc(1, 2, 3);
}, 1000);

Using the new Function() constructor is similar to eval() and should be approached with care. It could be a powerful construct but is often misused. If you absolutely must use eval(), you can consider using new Function() instead.

There is a small potential benefit because the code evaluated in new Function() will be running in a local function scope, so any variables defined with var in the code being evaluated will not become globals automatically.

Another way to prevent automatic globals is to wrap the eval() call into an immediate function.

Crashing answered 8/5, 2017 at 14:6 Comment(1)
Can you suggest how I might evaluate a function-local dynamic variable name without eval? Eval (and similar) functions are last-resorts in most languages that contain them, but sometimes it's necessary. In the case of getting a dynamic variable's name, is any solution more secure? In any case, javascript itself is not for real security (server-side is obviously the main defense). If you're interested, here's my use-case of eval, which I'd love to change: stackoverflow.com/a/48294208Vanadium
T
3

It greatly reduces your level of confidence about security.

Tallage answered 17/9, 2008 at 20:6 Comment(0)
B
3

If you want the user to input some logical functions and evaluate for AND the OR then the JavaScript eval function is perfect. I can accept two strings and eval(uate) string1 === string2, etc.

Bucella answered 9/3, 2010 at 14:28 Comment(1)
You can also use Function() {}, but be careful when using these on the server unless you want users to take over your server hahahah.Passus
F
2

Besides the possible security issues if you are executing user-submitted code, most of the time there's a better way that doesn't involve re-parsing the code every time it's executed. Anonymous functions or object properties can replace most uses of eval and are much safer and faster.

Fade answered 17/9, 2008 at 19:14 Comment(0)
A
2

This may become more of an issue as the next generation of browsers come out with some flavor of a JavaScript compiler. Code executed via Eval may not perform as well as the rest of your JavaScript against these newer browsers. Someone should do some profiling.

Alchemist answered 17/9, 2008 at 19:20 Comment(0)
S
2

This is one of good articles talking about eval and how it is not an evil: http://www.nczonline.net/blog/2013/06/25/eval-isnt-evil-just-misunderstood/

I’m not saying you should go run out and start using eval() everywhere. In fact, there are very few good use cases for running eval() at all. There are definitely concerns with code clarity, debugability, and certainly performance that should not be overlooked. But you shouldn’t be afraid to use it when you have a case where eval() makes sense. Try not using it first, but don’t let anyone scare you into thinking your code is more fragile or less secure when eval() is used appropriately.

Solvable answered 8/10, 2014 at 9:4 Comment(0)
S
2

eval() is very powerful and can be used to execute a JS statement or evaluate an expression. But the question isn't about the uses of eval() but lets just say some how the string you running with eval() is affected by a malicious party. At the end you will be running malicious code. With power comes great responsibility. So use it wisely is you are using it. This isn't related much to eval() function but this article has pretty good information: http://blogs.popart.com/2009/07/javascript-injection-attacks/ If you are looking for the basics of eval() look here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval

Stagemanage answered 25/10, 2014 at 15:17 Comment(0)
B
2

The JavaScript Engine has a number of performance optimizations that it performs during the compilation phase. Some of these boil down to being able to essentially statically analyze the code as it lexes, and pre-determine where all the variable and function declarations are, so that it takes less effort to resolve identifiers during execution.

But if the Engine finds an eval(..) in the code, it essentially has to assume that all its awareness of identifier location may be invalid, because it cannot know at lexing time exactly what code you may pass to eval(..) to modify the lexical scope, or the contents of the object you may pass to with to create a new lexical scope to be consulted.

In other words, in the pessimistic sense, most of those optimizations it would make are pointless if eval(..) is present, so it simply doesn't perform the optimizations at all.

This explains it all.

Reference :

https://github.com/getify/You-Dont-Know-JS/blob/master/scope%20&%20closures/ch2.md#eval

https://github.com/getify/You-Dont-Know-JS/blob/master/scope%20&%20closures/ch2.md#performance

Bosworth answered 30/1, 2016 at 6:34 Comment(1)
No javascript engine cannot find and eval in the code with 100% guarantee. Therefore, it must be ready for it at any time.Specialize
H
2

It's not always a bad idea. Take for example, code generation. I recently wrote a library called Hyperbars which bridges the gap between virtual-dom and handlebars. It does this by parsing a handlebars template and converting it to hyperscript which is subsequently used by virtual-dom. The hyperscript is generated as a string first and before returning it, eval() it to turn it into executable code. I have found eval() in this particular situation the exact opposite of evil.

Basically from

<div>
    {{#each names}}
        <span>{{this}}</span>
    {{/each}}
</div>

To this

(function (state) {
    var Runtime = Hyperbars.Runtime;
    var context = state;
    return h('div', {}, [Runtime.each(context['names'], context, function (context, parent, options) {
        return [h('span', {}, [options['@index'], context])]
    })])
}.bind({}))

The performance of eval() isn't an issue in a situation like this because you only need to interpret the generated string once and then reuse the executable output many times over.

You can see how the code generation was achieved if you're curious here.

Hercegovina answered 28/11, 2016 at 11:4 Comment(0)
V
2

I would go as far as to say that it doesn't really matter if you use eval() in javascript which is run in browsers.*(caveat)

All modern browsers have a developer console where you can execute arbitrary javascript anyway and any semi-smart developer can look at your JS source and put whatever bits of it they need to into the dev console to do what they wish.

*As long as your server endpoints have the correct validation & sanitisation of user supplied values, it should not matter what gets parsed and eval'd in your client side javascript.

If you were to ask if it's suitable to use eval() in PHP however, the answer is NO, unless you whitelist any values which may be passed to your eval statement.

Valuator answered 1/3, 2018 at 11:30 Comment(0)
B
2

EDIT: As Benjie's comment suggests, this no longer seems to be the case in chrome v108, it would seem that chrome can now handle garbage collection of evaled scripts.

VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV

Garbage collection

The browsers garbage collection has no idea if the code that's eval'ed can be removed from memory so it just keeps it stored until the page is reloaded. Not too bad if your users are only on your page shortly, but it can be a problem for webapp's.

Here's a script to demo the problem

https://jsfiddle.net/CynderRnAsh/qux1osnw/

document.getElementById("evalLeak").onclick = (e) => {
  for(let x = 0; x < 100; x++) {
    eval(x.toString());
  }
};

Something as simple as the above code causes a small amount of memory to be store until the app dies. This is worse when the evaled script is a giant function, and called on interval.

Bittersweet answered 13/8, 2019 at 4:32 Comment(2)
This does not seem to be the case in Chrome v108, which runs the V8 JS engine, same as Node. Though the eval version seems to climb slightly faster, it took around 80 seconds for it to hit 10MB and then it garbage collected back down to the starting amount and continued running. Clicking the trashcan icon at the top left ("Collect garbage") also has the same effect of resetting the memory usage back to the original value. There doesn't appear to be any leakage.Fahlband
Just tested it and you are correct, seems like this might no longer be the case. Thanks @FahlbandBittersweet
J
0

I won't attempt to refute anything said heretofore, but i will offer this use of eval() that (as far as I know) can't be done any other way. There's probably other ways to code this, and probably ways to optimize it, but this is done longhand and without any bells and whistles for clarity sake to illustrate a use of eval that really doesn't have any other alternatives. That is: dynamical (or more accurately) programmically-created object names (as opposed to values).

//Place this in a common/global JS lib:
var NS = function(namespace){
    var namespaceParts = String(namespace).split(".");
    var namespaceToTest = "";
    for(var i = 0; i < namespaceParts.length; i++){
        if(i === 0){
            namespaceToTest = namespaceParts[i];
        }
        else{
            namespaceToTest = namespaceToTest + "." + namespaceParts[i];
        }

        if(eval('typeof ' + namespaceToTest) === "undefined"){
            eval(namespaceToTest + ' = {}');
        }
    }
    return eval(namespace);
}


//Then, use this in your class definition libs:
NS('Root.Namespace').Class = function(settings){
  //Class constructor code here
}
//some generic method:
Root.Namespace.Class.prototype.Method = function(args){
    //Code goes here
    //this.MyOtherMethod("foo"));  // => "foo"
    return true;
}


//Then, in your applications, use this to instantiate an instance of your class:
var anInstanceOfClass = new Root.Namespace.Class(settings);

EDIT: by the way, I wouldn't suggest (for all the security reasons pointed out heretofore) that you base you object names on user input. I can't imagine any good reason you'd want to do that though. Still, thought I'd point it out that it wouldn't be a good idea :)

Judicative answered 12/2, 2015 at 18:45 Comment(1)
this can be done with namespaceToTest[namespaceParts[i]], no need for eval here, so the if(typeof namespaceToTest[namespaceParts[i]] === 'undefined') { namespaceToTest[namespaceParts[i]] = {}; the only difference for the else namespaceToTest = namespaceToTest[namespaceParts[i]];Taxpayer

© 2022 - 2024 — McMap. All rights reserved.