我怎么能有一个JS应用程序内的受保护的范围,它不会受到任何其他function的影响?

我有一个函数接受另一个函数作为参数。 外部函数是否可能在不知道它做什么的情况下运行内部函数,并避免尝试对受保护作用域中的任何variables进行任何更改。

注:通过保护,我不是指在Java,C ++或C#中可用的受保护的inheritance范围说明符。

例:

假设我有一个function处理器。

{ // processor is a function of an object which has input and output be parameters function processor(functionToExecute) { this.output = functionToExecute(this.input); } } 

现在我不知道什么代码,functionToExecute将运行。

我在全球范围内有几个variablesa,b或c。 我不希望它们受到影响,或者在全局范围内的任何其他函数被从functionToBeExecuted调用。 我只是想让它接受参数并给出输出。

但不应该能够产生影响范围之外的任何副作用。

理想情况下,我将从用户那里询问这个函数,并在服务器上运行它来处理用户想要的一段数据。

函数的作用域在声明时被确定,而不是被执行。

 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 }); 

而且,全局variables在代码中的任何地方都是可见的。 任何代码都可以修改全局variables,除了一些情况,比如WebWorkers,但这是另一回事。

下面是一个如何使用立即函数来隐藏值的例子,并且只展示函数来使用它们:

 (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 

但是对于对象,它们是通过引用传递的。 一旦你通过他们的地方,他们可能会被修改。