I have two javascript docs on my project. js (script.js) #1:
let func = new Function('return thisvar')
console.log(func())
js (script1.js) #2:
let thisvar = 'hello'
I get an error:
ERROR:{@script.js line 4: cannot find variable 'thisvar'}
I have tried using var instead of let or even window.thisvar
What am I doing wrong?
When you run func() in your first script, you haven't yet defined thisvar.
Just move the function call to your second script after you define the variable.
let func = new Function('return thisvar')
let thisvar = 'hello'
console.log(func())
Readable "hello world" example (The console.log(func(your_error) return the same error - cannot find variable (You didn't declare the 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>
In general it is more efficient to use function expression or function statement.
Read more here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/Function