(1,EVAL)('这')VS eval('这')在JavaScript呢?

Leva7shawjia提出了一个问题:(1, eval)('this') vs eval('this') in JavaScript?,或许与您遇到的问题类似。

回答者Malvolio给出了该问题的处理方式:

The difference between (1,eval) and plain old eval is that the former is a value and the latter is an lvalue. It would be more obvious if it were some other identifier:

var x;
x = 1;
(1, x) = 1; //  syntax error, of course!

That is (1,eval) is an expression that yields eval (just as say, (true && eval) or (0 ? 0 : eval) would), but it's not a reference to eval.

Why do you care?

Well, the Ecma spec considers a reference to eval to be a "direct eval call", but an expression that merely yields eval to be an indirect one -- and indirect eval calls are guaranteed to execute in global scope.

Things I still don't know:

  1. Under what circumstance does a direct eval call not execute in global scope?
  2. Under what circumstance can the this of a function at global scope not yield the global object?

Some more information can be gleaned here.

EDIT

Apparently, the answer to my first question is, "almost always". A direct eval executes from the current scope. Consider the following code:

var x = 'outer';
(function() {
  var x = 'inner';
  eval('console.log("direct call: " + x)'); 
  (1,eval)('console.log("indirect call: " + x)'); 
})();

Not surprisingly (heh-heh), this prints out:

direct call: inner
indirect call: outer

EDIT

After more experimentation, I'm going to provisionally say that this cannot be set to null or undefined. It can be set to other falsy values (0, '', NaN, false), but only very deliberately.

I'm going to say your source is suffering from a mild and reversible cranio-rectal inversion and might want to consider spending a week programming in Haskell.

希望本文对你有帮助,欢迎支持JavaScript中文网

原文链接:stackoverflow.com

上一篇:在淘汰赛视图-嵌套上下文中访问父$双亲
下一篇:JavaScript(+)符号连接而不是给予和变量

相关推荐

官方社区

扫码加入 JavaScript 社区