Tengo dos documentos javascript en mi proyecto. js (script.js) #1:
let func = new Function('return thisvar') console.log(func())js (script1.js) #2:
let thisvar = 'hello' Recibo un error: ERROR:{@script.js line 4: cannot find variable 'thisvar'} Intenté usar var en lugar de let o incluso window.thisvar ¿Qué estoy haciendo mal?
Cuando ejecuta func() en su primer script, aún no ha definido thisvar .
Simplemente mueva la llamada de función a su segundo script después de definir la variable.
let func = new Function('return thisvar') let thisvar = 'hello' console.log(func())Ejemplo legible de "hola mundo" (La console.log(func(your_error) devuelve el mismo error: no se puede encontrar la variable (no declaraste la variable).
<span>example</span> <script> let func = new Function("arg1", "return arg1") let thisvar = 'hello'; /* missing in your code */ console.log(func(thisvar)) // expected output: hello console.log(func("world")) // expected output: world console.log(func(your_error)) // expected output: "Uncaught ReferenceError: your_error is not defined" </script>En general, es más eficiente usar expresión de función o instrucción de función.
Lea más aquí: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/Function