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

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

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

The difference between (1,eval)and plain old evalis that the former is a valueand 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 referenceto evalto be a "direct eval call", but an expression that merely yields evalto 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 notexecute in global scope?
  2. Under what circumstance can the thisof a function at global scope notyield the global object?

Some more information can be gleaned here.

EDIT

Apparently, the answer to my first question is, "almost always". A direct evalexecutes from the currentscope. 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 thiscannot be set to nullor undefined. It can be set to other falsy values (0, '', NaN, false), but only verydeliberately.

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 社区