JavaScript中的(1,eval)('this')vs eval('this')? [英] (1, eval)('this') vs eval('this') in JavaScript?

查看:126
本文介绍了JavaScript中的(1,eval)('this')vs eval('this')?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开始阅读 JavaScript模式,其中一些代码让我困惑。

I start to read JavaScript Patterns, some codes confused me.

var global = (function () {
    return this || (1, eval)('this');
}());

以下是我的问题:

Q1 :


(1,eval)=== eval

为什么以及如何运作?

Why and how does it work?

Q2:为什么不只是

var global = (function () {
    return this || eval('this');
}());

 var global = (function () {
    return this;
}());


推荐答案

之间的区别(1 ,eval)和普通旧 eval 前者是,后者是左值。如果它是其他标识符会更加明显:

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!

那是(1,eval)是产生 eval 的表达式(就像说,(true&& eval)(0?0:eval) will),但它不是对 eval 的引用。

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.

你为什么关心?

好吧,Ecma规范认为引用 eval 是一个直接eval调用,但表达式只是将 eval 作为间接调用 - 并且间接eval调用保证在全局执行范围。

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.

我还不知道的事情:


  1. 在什么情况下直接评估在全球范围内执行吗?

  2. 在什么情况下这个的全局范围内的函数产生全局对象?

  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?

可以收集更多信息在其他地方

编辑

显然,我的第一个问题的答案是几乎总是。直接 eval 当前范围执行。请考虑以下代码:

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

编辑

经过更多实验,我暂时会说这个不能设置为 null undefined 。它可以设置为其他虚假值(0,'',NaN,false),但只有非常故意。

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.

我要去说你的来源患有轻度和可逆的颅内直肠反转,并且可能想考虑在Haskell中花一周时间编程。

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中的(1,eval)('this')vs eval('this')?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆