简体   繁体   English

与eval()等效的JavaScript构造

[英]JavaScript constructs equivalent to eval()

In JavaScript, eval() takes a string and executes it as JavaScript code, eg, 在JavaScript中, eval()接受一个字符串并将其作为JavaScript代码执行,例如,

eval( "alert('I am parsed as JavaScript code.');");

I am interested in what constructs out there, other than eval() , can potentially be used for the same purpose. 我对除eval()之外的其他构造可用于同一目的感兴趣。 I know eval() is evil. 我知道eval()是邪恶的。 This is for educational purposes. 这是出于教育目的。

So far I have found three such constructs: 到目前为止,我已经发现了三个这样的构造:

  1. The Function constructor: Function构造函数:

     var f = new Function( "alert('I am also parsed as JavaScript code.');"); f(); 
  2. The setTimeout() function: setTimeout()函数:

     setTimeout( "alert('So am I.');", 0); 
  3. The setInterval() function: setInterval()函数:

     setInterval( "alert('Me too!');", 0); 

Are there other constructs that can be used to achieve this behavior? 是否有其他可用于实现此行为的构造? If yes, which ones? 如果是,哪个? If no, any good references to substantiate that claim? 如果否,是否有充分的证据证明这一主张?

Sort of obscure, but so long as the page hasn't finished loading yet... 有点晦涩,但是只要页面尚未完成加载...

document.body.setAttribute("onLoad","alert('Hello world!');");

Not that anyone would do that. 并不是说有人会那样做。 Right? 对?

Any function constructor will do: 任何函数构造函数都可以:

 console.log.constructor("alert(\\"hello\\")")() 

or 要么

 (c=>Function(c))("alert (\\"hello again\\")")() 

or 要么

 (_=>_('alert("hello")'))(Array.constructor)() 

or 要么

 document.body.setAttribute("onmousemove","this.onmousemove=null;alert('hello')"); 
 <html> <head> </head> <body width="100%" hoight="100%"> hello </body> </html> 

在此处输入图片说明

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

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