Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How eval in JavaScript changes the calling context?

Tags:

javascript

On dynamic property of JavaScript is that "eval" changes the calling context. What does it mean? Some examples would be better.

like image 728
dalibocai Avatar asked Feb 22 '26 15:02

dalibocai


1 Answers

eval does change the context when called indirectly. And it changes it to the global context (the default context for all functions).

var myObj = { a: 1 }

function someFunc() {
    console.log(eval('this.a')) // 1
    console.log(eval('this === myObj')) // true

    var indirectEval = eval

    console.log(indirectEval('this.a')) // undefined
    console.log(indirectEval('this === window')) // true
}

void someFunc.call(myObj)

Direct eval calls don't change the context (nor do they change the scope).

See “Global eval. What are the options?” for details.

like image 174
katspaugh Avatar answered Feb 25 '26 03:02

katspaugh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!