Global Eval with return value ? - javascript

After searching a while , I was hoping to find a solution for global eval with a return value.
eval will run in the current scope
Function constructor will execute in its own local scope with access to global scope
setTimeout trick is an async operation
script injection can not return value
window.execScript also - can not return value
So my question is:
Is there any other technique which runs at the global scope and can return value ?
(example will be much appreciated).

You can make eval to run in global scope, instead of
eval(s)
just use
window.eval(s);
or
var e=eval; e(s);
or
[eval][0](s)
This surprisingly happens because Javascript is weird and has a special rule about eval: when you're using the original eval object directly to evaluate a string the evaluation happens in the current context.
If an "indirect eval" is used instead (i.e. you store eval in a variable and then use the variable, or even if you access eval using the window object) the evaluation happens in the global context.
You can check this in a Javascript console:
function foo() {
eval("function square(x){ return x*x; }");
}
function bar() {
window.eval("function square(x){ return x*x; }");
}
foo()
square(12) // <-- this gives an error; direct evaluation was used
bar()
square(12) // <-- this returns 144
So window.eval(s) is not the same as eval(s) even if window.eval === eval.
PS
Note that eval has a special specific language rule for this to happen, but the same apparently strange behavior can also be observed in other cases for a different reason.
If you have an object x with a method defined m then
x.m()
is not the same as
var mm = x.m; mm();
because this in the first case will be bound to x during execution of the code in m while in the second case this will be the global object.
So also in this case x.m() is different from mm() even if x.m === mm.
For the same reason x.m() is not the same as [x.m][0]() because in the latter this will be bound to an array object during the execution of method code instead of being bound to x.

Related

How to run Global Constant Function from Variable in Browser

I can access and run any function resides in window Object Using name String.
for e.g,
function abc() {
console.log("abc");
}
var str = "abc";
window[str](); // abc
but I want to know, is it somehow possible to run function declared with const keyword.
const xyz = () => console.log("xyz");
const str = "xyz";
window[str](); // TypeError: window.xyz is not a function
It's possible, but the only way to do it I can think of is a Bad Idea™ in most cases: eval or its close cousin new Function:
const xyz = () => console.log("xyz");
const str = "xyz";
(0,eval)(str + "()");
new Function(str + "()")();
The problem with eval (whether direct or, as above, indirect) and new Function is that they run arbitrary code from a string, firing up a full JavaScript parser to do so. Used incorrectly, that opens the door to XSS attacks or issues with inefficient code (though parsers are amazingly fast these days).
For any who don't know (I think the OP does): Global const, let, and class bindings are not added as properties to the global object like global var and function bindings are. That's why window[str](); won't work.
About
(0,eval)(str + "()");
above: that's an indirect eval. It works by separating the lookup of the identifier eval from the call, which breaks eval's special link with local scope. In that case, it's using the comma operator to do that. Details:
You probably know that eval has access to local scope (and all containing scopes), so for instance this works:
function foo() {
const answer = 42;
eval("console.log(answer);");
}
foo();
The code in eval can see answer because it has access to the scope where you called eval.
To try to limit the power of eval a bit, you can turn off its access to local scope and have it run its code at global scope instead by using eval indirectly. For instance, if you put it in a variable:
function foo() {
const answer = 42;
const e = eval;
e("console.log(answer);"); // Fails with ReferenceError
}
foo();
By separating the lookup of the identifier eval from calling the function it refers to, you break the special link it has with local scope.
The comma operator is one of JavaScript's more unusual operators: It evalutes its left-hand operand, throws away the result, evaluates its right-hand operand, and takes that value as the result of the comma expression:
function foo() {
console.log("foo ran and returned 1");
return 1;
}
function bar() {
console.log("bar ran and returned 2");
return 2;
}
const x = (foo(), bar());
console.log(`x = ${x}`);
Using (0, eval)(str) separates the lookup of the identifier eval from the call to the function just like assigning it to e did above. 0 is evaluated, thrown away, then eval is evaluated resulting in a function reference, and that function reference is the result of the comma expression; then we use it to eval str.

Does execution of eval() will only be known (scoped) inside the function where it is called?

function executer(text){
var result = eval(text);
}
executer("var _sc_a=5");
executer("_sc_a>6");
The second call of executer return me an "undefined" result, is this because of that in the 2nd call, eval doesnt know that _sc_a=5 is initialized? How should i make the first call known to the 2nd call of executer?
UPDATE: The project im working on is a C++ Web-based translator that has the capability to evaluate conditional expr, trace variable values and show the interpreter-reading flow (loop statements)
I have a next button that will translate/evaluate/execute fragments step by step as the user click on next
fragment[0]="var a=0,b;";//already translated from "int a=0,b;"
fragment[1]="a=5;";
fragment[2]="((a>1)&&(a<10));";
$('#next').click(function(e) {
//setting of ctr here to decide which fragment element should be called
current(fragment[ctr]);
});
function current(text){
try{
eval(text);
}
catch(err){
alert("Eval error found");
}
}
Since you run direct eval under nonstrict, tldr version is that you are running code equivalent to this:
function executer(text) {
var result;
var _sc_a = 5;
}
_sc_a > 6;
So it's easy to see why the second eval doesn't work like you intend.
The issue is complicated, yes, if you call eval directly and in non strict mode, it will introduce variables locally. So you need strict mode to get lexical scoping.
If you did that in strict mode, the variable would not be known anywhere.
If you did that by calling eval indirectly in non-strict mode, it would introduce a global variable.
If you did that by calling eval indirectly in strict mode, it would not again introduce any new variables.
Yes. eval() is scoped to the executer() function and you are initializing outside of that function's context.

return this || (0,eval)('this');

Looking at the doT.js source:
https://raw.github.com/olado/doT/master/doT.js
What does this do?
(function(){ return this || (0,eval)('this'); }()).doT = doT;
To me it looks like it's creating a global var, window.doT. If that's all it's doing, then why not:
window.doT = doT;
?
It's getting a reference to the global object, in order to assign doT to it. This is generally done because with a JavaScript library/framework/etc, its one global identifier needs to be exposed to the outside world.
As for why it's not simply window.doT = doT;, it's because the global object isn't always window, for example, in a non-browser environment. It's also possible to have window assigned to somewhere else at the point this code is executed.
How it works
If this is already truthy, for example, an object such as window, it will return that. It's likely it will be window (at least in the browser), as a plain function call should have its ThisBinding set to the global object. Otherwise, it will execute eval() in the global scope because an indirect call to eval() will set its scope to global, as opposed to the calling environment's scope.
To achieve an indirect call, you have to invoke eval() indirectly, i.e. you can't just call it with eval(). You can use (0, eval) to invoke it. This relies on the comma operator returning the last evaluated expression, in this case eval. It doesn't matter what the preceding operands are. Similarly, (0||eval)() would work.
As for why the body is this, that is the argument to eval(), that is the code to be executed as a string. It will return the this in the global scope, which is always the global object.
It's not really relevant nowadays, but in older IEs, you'd need to use execScript() to execute code in the global scope. I can't remember exactly what versions of IE this was necessary for.
Only adding a bit to the accepted answer as the last question in the condensed comments view "wouldn't (eval)('this') work as well?" has its answer lost in the comment chatter. Simple test:
> foo = 123
< 123
> (function() { const foo = 234; console.log(
foo, // baseline
eval('foo'), // direct eval using local scope
(eval)('foo'), // (eval) still direct
(1, eval)('foo'), // indirect by comma-operator
(false||eval)('foo')); // indirect by or-operator
})()
< 234 234 234 123 123
It shows that
(eval) is not the same as (0, eval) (or, here, (1,eval)) because the comma operator is indirect whereas the parenthesis is not indirect, just a syntactic grouping, the mere parenthesis does not pass its argument through an operation, so it remains direct.
the (false||eval) approach relies on the argument before being falsy, therefore the comma operator is better, it matters less what that first value is.
To me the comma-operator was the biggest aha here, that's why I was dwelling on it a bit.
I have a concern also, i.e., that this trick would by accident be used from a function that might be added to a prototype as a method. In that case the first this is no longer the global object. Which is why, to be really safe, in my opinion one should just stick with the (0,eval)('this') expression only.

(1, eval)('this') vs eval('this') in JavaScript?

I start to read JavaScript Patterns, some codes confused me.
var global = (function () {
return this || (1, eval)('this');
}());
Here are my questions:
Q1:
(1, eval) === eval?
Why and how does it work?
Q2: Why not just
var global = (function () {
return this || eval('this');
}());
or
var global = (function () {
return this;
}());
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!
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 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.
Things I still don't know:
Under what circumstance does a direct eval call not execute in global scope?
Under what circumstance can the this of a function at global scope not yield the global object?
Some more information can be gleaned here.
EDIT
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
EDIT
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.
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.
The fragment
var global = (function () {
return this || (1, eval)('this');
}());
will correctly evaluate to the global object even in strict mode. In non-strict mode the value of this is the global object but in strict mode it is undefined. The expression (1, eval)('this') will always be the global object.
The reason for this involves the rules around indirect versus direct eval. Direct calls to eval has the scope of the caller and the string this would evaluate to the value of this in the closure. Indirect evals evaluate in global scope as if they were executed inside a function in the global scope.
Since that function is not itself a strict-mode function the global object is passed in as this and then the expression 'this' evaluates to the global object. The expression (1, eval) is just a fancy way to force the eval to be indirect and return the global object.
A1: (1, eval)('this') is not the same as eval('this') because of the special rules around indirect versus direct calls to eval.
A2: The original works in strict mode, the modified versions do not.
To Q1:
I think this is a good example of comma operator in JS. I like the explanation for comma operator in this article: http://javascriptweblog.wordpress.com/2011/04/04/the-javascript-comma-operator/
The comma operator evaluates both of its operands (from left to right) and returns the value of the second operand.
To Q2:
(1, eval)('this') is considered as indirect eval call, which in ES5 does execute code globally. So the result will be the global the context.
See http://perfectionkills.com/global-eval-what-are-the-options/#evaling_in_global_scope
Q1: Multiple consecutive javascript statements separated by a comma take the value of the last statement. So:
(1, eval) takes the value of the last one which is a function reference to the eval() function. It apparently does it this way to make the eval() call into an indirect eval call that will be evaluated in the global scope in ES5. Details explained here.
Q2: There must be some environment that doesn't define a global this, but does define eval('this'). That's the only reason I can think of for that.

Javascript - Do I need to use 'var' when reassigning a variable defined in the function's parameters?

I've found many definitions of the 'var' statement but most of them are incomplete (usually from introductory guides/tutorials). Should I use 'var' if the variable & scope has been declared in the params list?
someFunc = function(someVar)
{
// Is it considered good practice to use 'var', even if it is redundant?
var someVar = cheese;
};
The answer is no, you shouldn’t be doing this. This is actually considered a bad practice!
JS Lint throws the following error when analyzing your code example:
Problem at line 5 character 16: someVar is already defined.
"I've found many definitions of the 'var' statement but most of them are incomplete."
Try this (a bit stuffy but hopefully complete :-) ): The var keyword declares a new variable, binds it to the current lexical scope, & hoists it to the top of said scope. In other words, the variable will not exist outside of the function that declares it & will be declared before any statements are executed inside the function. Function parameters are implicitly bound to that function's scope so do not require the var keyword.
Nope, the order in which names are defined when entering an execution scope is as follows:
function parameters (with value passed or undefined)
special name arguments (with value of arguments if doesn't exist)
function declarations (with body brought along)
variable declarations (with undefined if doesn't exist)
name of current function (with body brought along, if doesn't exist)
This means that in this code, foo refers to the function parameter (which could easily be changed):
function foo(foo) {
var foo;
alert(foo);
}
foo(1); // 1
If you're using a function declaration inside for foo, that body will override all others. Also, note that this means that you can do this:
function foo(arguments) {
alert(arguments);
}
foo(); // undefined
foo(1); // 1
Don't do that.
No. In Javascript, you can mess with the function argument all you want.
Consider this code, which you see all over the Web and which is used to make code work in standard and IE event models:
function someEventHandler(event) {
event= (event) ? event : window.event;
// statements
}

Categories

Resources