简体   繁体   English

为什么在eval()中的typeof会在我的函数中抛出错误?

[英]Why does typeof within eval() throw an error in my function?

I was trying to implement a function similar to angular.isDefined(...) 我试图实现类似于angular.isDefined(...)的函数

but allowing to check variables and their properties, so I wrote this proof of concept: 但是允许检查变量及其属性,所以我写了这个概念证明:

 function check(s) { let parts = s.split('\\.'); let partial = ''; return parts.every(p => { partial += (partial ? '.': '') + p; let expr = `typeof ${partial}`; console.log('Evaluating', expr); return eval(expr) !== 'undefined'; }); } check('obj'); let obj={}; check('obj'); obj.a=1; check('obj.a'); 

I know that typeof allows a non declared identifier, and it seems to work properly within eval() : 我知道typeof允许一个非声明的标识符,它似乎在eval()正常工作:

 console.log(typeof someVariableWhichDoesNotExists) console.log(eval('typeof someVariableWhichDoesNotExists')); 

But in my code fails when it is processed by eval() . 但是当我的代码在eval()处理时失败了。 What am I missing? 我错过了什么?

PS: I've read Why does typeof only sometimes throw ReferenceError? PS:我读过为什么typeof有时会抛出ReferenceError? but I think it is not the same scenario, I am not checking an expression here, but just a identifier. 但我认为这不是同一个场景,我不是在这里检查一个表达式,而只是一个标识符。

This actually has nothing to do with eval() . 这实际上与eval()无关。 Your error is caused by defining let obj but trying to use it before it is defined. 您的错误是由定义let obj但在定义之前尝试使用它引起的。 This exception is described here : 此处描述此异常:

But with the addition of block-scoped let and const, using typeof on let and const variables (or using typeof on a class) in a block before they are declared will throw a ReferenceError. 但是通过添加块范围的let和const,在声明它们之前在块中使用typeof on let和const变量(或在类上使用typeof)将抛出ReferenceError。 Block scoped variables are in a "temporal dead zone" from the start of the block until the initialization is processed, during which, it will throw an error if accessed 块范围变量在块的开始处于“临时死区”,直到处理初始化,在此期间,如果访问初始化,它将引发错误

You can cause this error easily without eval() : 如果没有eval()您可以轻松地导致此错误:

 // undefined no problem because obj was not declared console.log(typeof obj) // undefined but variable declared with let // but not defined before using it results in an error console.log(typeof otherobj) let otherobj = {} 

Your error goes away if you remove the let obj={}; 如果你删除let obj={};你的错误就会消失let obj={}; declaration or use var obj = {} . 声明或使用var obj = {}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM