Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

96
Views
Prevent Stringifcation of Objects Passed Into Eval

Consider this code:

function set(n,v) {  // This is a setter
    eval(n+"="+v);
}

let one = 1;
function add1(num) {
    return num + one;
}

{
    let two = 2;
    set("add1", function(num) {
        return num + two;
    });

}

// Add 1 now equals: 
//  function(num) {
//      return num + two;
//  }

// So if we call add 1:
add1();

// We get a "Uncaught ReferenceError: two is not defined"

This is because eval stringifies the function which removes its connection to variables it counts on

How do I stop this (keep the set behavior, but prevent the function from leaving behind variables)

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

DON'T USE eval for variable variables. Use objects instead, as explained here

Now, to answer your question: as a direct eval can access your local variables, all you have to do is read them inside the eval string, instead of passing from the outside:

function set(n, v) {
    eval(n + "= v");
}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!