Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to restrict the scope of a javascript function?

Suppose I have a variables in the global scope.

Suppose I wish to define a function which I can guarantee will not have access to this variable, is there a way to wrap the function, or call the function, that will ensure this?

In fact, I need any prescribed function to have well defined access to variables, and that access to be defined prior to, and separate from that function definition.

Motivation: I'm considering the possibility of user submitted functions. I should be able to trust that the function is some variety of "safe" and therefore be happy publishing them on my own site.

like image 233
cammil Avatar asked Jan 26 '12 15:01

cammil


People also ask

What is the scope of JavaScript functions?

Scope in JavaScript refers to the current context of code, which determines the accessibility of variables to JavaScript. The two types of scope are local and global: Global variables are those declared outside of a block. Local variables are those declared inside of a block.

What is blocked scope in JavaScript?

Block Level Scope: This scope restricts the variable that is declared inside a specific block, from access by the outside of the block. The let & const keyword facilitates the variables to be block scoped. In order to access the variables of that specific block, we need to create an object for it.

What are the two types of scopes in JavaScript?

JavaScript has the following kinds of scopes: Global scope: The default scope for all code running in script mode. Module scope: The scope for code running in module mode.

Is Let block scoped in JavaScript?

The let declaration declares a block-scoped local variable, optionally initializing it to a value.


1 Answers

Run the code in an iframe hosted on a different Origin. This is the only way to guarantee that untrusted code is sandboxed and prevented from accessing globals or your page's DOM.

like image 72
josh3736 Avatar answered Sep 21 '22 23:09

josh3736