22

javascript eval: direct vs indirect call

 3 years ago
source link: https://blog.klipse.tech/javascript/2016/06/20/js-eval-secrets.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

javascript eval: direct vs indirect call

Jun 20, 2016 • Yehonathan Sharvit

Every javsacript developer knows that eval is evil.

But eval is really powerful and from a theoretical perspective eval is very interesting.

For instance, did you ever ask yourself in what context does eval run?

In this article, we are going to show a couple of examples that relates to this question.

Power

All the examples of this page are live and interactive code snippets:

  1. The code is executed in your browser
  2. You can modify the code and it is evaluated as you type

The interactive code snippets are powered by klipse.

Outside Scope or Inside Scope?

Usually, eval runs inside the scope of the caller function:

xxxxxxxxxx
var context = 'outside';
(function(){
  var context = 'inside';
  return eval('context');
})();
"inside"

But sometimes, eval runs outside the scope of the caller function:

xxxxxxxxxx
var context = 'outside';
(function(){
  var context = 'inside';
  return eval.call(null, 'context');
})();
xxxxxxxxxx
"outside"

Also in this case - outside:

xxxxxxxxxx
var context = 'outside';
(function(){
  var context = 'inside';
  return (1, eval)('context');
})();
xxxxxxxxxx
"outside"

But in this case - it’s inside:

xxxxxxxxxx
var context = 'outside';
(function(){
  var context = 'inside';
  return (eval)('context');
})();
xxxxxxxxxx
"inside"

And another one that gets outside:

xxxxxxxxxx
var context = 'outside';
(function(){
  var context = 'inside';
  var my_eval = eval;
  return my_eval('context');
})();
xxxxxxxxxx
"outside"

It depends whether the eval call is direct or indirect.

Furher details and explanations in this article that explains the difference between eval direct and indirect call in EcmaScript 5 and other cool stuff.


If you enjoy this kind of interactive articles would you consider a (small) donation💸 on Patreon or at least giving a star⭐ for the Klispe repo on Github?

Follow viebel to stay up-to-date with the coolest interactive articles around the world.

Discover more cool interactive articles about javascript, clojure[script], python, ruby, scheme, c++ and even brainfuck!

Give Klipse a Github star to express how much you appreciate Code Interactivity.

Subscribe to the Klipse newsletter:

Feel free to email me [email protected] for getting practical tips and tricks in writing your first interactive blog post.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK