void(document.body.innerText += 'hi')
eval(document.body.innerText +='\nbye')
Function(document.body.innerText += '\n!!!')
void(Function(function foo(){document.body.innerText += '\n>hi2'; return true}).toString())();
eval(Function(function foo(){document.body.innerText += '\nbye2'; return true}).toString())();
Function(Function(function foo(){document.body.innerText += '\n!!!2'; return true}).toString())();
What's the processing model for executing code within these different statements?
void(alert('hi'))
undefined
eval(alert('hi'))
undefined
Function(alert('hi'))
function anonymous() {
undefined
}
eval(Function(function foo(){return true}).toString())();
TypeError: undefined is not a function
void(Function(function foo(){return true}).toString())();
TypeError: string is not a function
Function(Function(function foo(){return true}).toString())();
undefined
In this article the eval
and Function
constructors are explained:
(…) Global, built-in
eval
function evaluates code in the scope of a caller.The code executed from within function created by
Function
constructor doesn’t really execute in global scope. However, it doesn’t execute in local scope either, which is what probably leads to confusion.Function
constructor creates a function whose scope chain consists of nothing but a global scope (preceded with function’s own Activation Object, of course). Any code contained in a function created viaFunction
constructor evaluates in a scope of that function, not in a global scope. However, it’s almost as if code executes globally, since global object is the very next object in the scope chain.
And according to this page, void
just returns undefined
:
In many languages,
void
is a type that has no values. In JavaScript,void
is an operator that takes an operand and returnsundefined
. This is not useful, and it is very confusing. Avoidvoid
.