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
Cómo configurar una variable local desde una nueva función en JavaScript

Tengo una función con una variable. Necesito ejecutar código desde una cadena para modificar esa variable. ¿Cómo configuraría una variable local desde new Function() o algo similar?

 function alertNumber() { var number = 5; var f = new Function("number = 4"); f(); console.log("local " + number); //should alert 4 console.log("window " + window.number); //instead of the local variable, it sets the property to the window } alertNumber();

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

0

Con new Function , no es posible.

Sin embargo, a diferencia de eval (que puede tener acceso al ámbito local), el constructor de funciones crea funciones que se ejecutan únicamente en el ámbito global.

necesitarías

 function alertNumber() { var number = 5; eval("number = 4"); console.log("local " + number); //should alert 4 } alertNumber();

(aunque tener que hacer esto en primer lugar es bastante sospechoso; si fuera yo, lo consideraría difícil si realmente no hubiera alternativas primero)

about 4 years ago · Juan Pablo Isaza Report

0

Simplemente cree una nueva función que modifique el número y luego devuelva el resultado del número modificado:

 // This should fix your problem function modifyNumber(number) { return number = 4 } function alertNumber() { var number = 5 number = modifyNumber(number) console.log("local " + number) // outputs "local 4" }
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!