eval two codes in same context in javascript

My goal is to allow the user to enter lines of code at different moments and have them add up in the same context, but I want to run them in a new context to prevent this from being window.

I tried this but I see the changes made to the context aren't kept:

var context = {};
var run = new Function("console.log(this === context);var a = 3");
run.call(context); // outputs 'true'
var run = new Function("console.log(a)");
run.call(context); // fails with 'a is not defined', I hoped it would write '3'

Is there some way I can achieve this?

Answers


Scope and context are completely different things, and eval doesn't enter into it. Your code is identical to

var run = function () { console.log(this === context);var a = 3);

There is no way to access a outside the function. The scope where a is declared isn't the calling scope, it's the functions own scope, and as written a has nothing to do with either this or context.

If you want two functions to share context, you need to use this.a = 3, not var a = 3.


Need Your Help

How I get the C# class real name?

c# obfuscation deobfuscation

I have a program in which I have encrypted my class names:

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.