I have a function that accepts another function as a parameter. Is it possible for the outer function to run the inner function without knowing what it does and avoid any changes it tries to make to any variable in the protected scope.
Note: By protected, I am not referring to the protected inheritance scope specifier available in Java,C++ or C#.
Example:
Suppose I have a function processor.
{
// processor is a function of an object which has input and output be parameters
function processor(functionToExecute)
{
this.output = functionToExecute(this.input);
}
}
Now I don't know what code, does functionToExecute will run.
I have few variables a,b or c at global scope. I dont want them to be affected or any other function at global scope to be called from functionToBeExecuted. I just want it to accept parameters and give the output.
but should not be able to have a side effect that affects anything outside its scope.
Ideally I will be asking this function as from the user and run it on the server to process a piece of data as the user wants.
The scope of a function is determined at the time it is declared, not when it is executed.
var a = 1;
var b = 2;
var b = 3;
function foo(fn){
//JS is function-scoped. It's the only way you can create a new scope.
//This is a new scope. It cannot be accessed from the outside
var a = 4;
var b = 5;
var b = 6;
//We call the passed function. Unless we pass it some references from this scope
//the function can never touch anything inside this scope
fn('hello world');
}
foo(function(hw,obj){
//the function passed is defined here where, one scope out, is the global scope
//which is also where a, b and c are defined. I can *see* them, thus they are
//modifiable
console.log(a,b,c); //123
a = 7;
b = 8;
c = 9;
console.log(a,b,c); //789
console.log(hw); //hello world
});
Also, globals are visible anywhere in the code. Any code can modify globals, except for some cases, like WebWorkers but that's another story.
Here's an example of how to use an immediate function to hide values, and only expose functions to use them:
(function(ns){
var width = 320;
var height = 240;
ns.getArea = function(fn){
fn.call(null,320 * 240);
}
}(this.ns = this.ns || {}));
//let's get the area
ns.getArea(function(area){
console.log(area);
});
//In this example, we have no way to modify width and height since it lives inside
//a scope that we can't access. It's modifiable only from within the scope
//or using a "setter" approach like in classical OOP
But for objects, they are passed by reference. Once you pass them somewhere, they can possibly be modified.