【问题标题】:How can I have a protected scope inside a JS application which in no way can get affected by any other function?如何在 JS 应用程序中拥有一个不受任何其他功能影响的受保护范围?
【发布时间】:2023-03-07 10:49:01
【问题描述】:

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

注意:我所说的受保护,并不是指 Java、C++ 或 C# 中可用的受保护继承范围说明符。

示例:

假设我有一个函数处理器。

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

}

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

我在全局范围内几乎没有变量 a、b 或 c。 我不希望它们受到影响,也不希望从 functionToBeExecuted 调用全局范围内的任何其他函数。 我只是想让它接受参数并给出输出。

但不应产生影响其范围之外的任何事物的副作用。

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

【问题讨论】:

  • 您传入的函数已经具有不同的范围,您不会对外部函数进行任何更改...您可以发布一些代码,也许我不明白这个想法。 ..
  • 受保护是什么意思?
  • 现在检查。我添加了一个示例和我的意图。
  • 您要查找的关键字是sandboxing

标签: javascript node.js


【解决方案1】:

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

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

});

此外,全局变量在代码中任何地方都是可见的。任何代码都可以修改全局变量,除了某些情况,比如 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

但是对于对象,它们是通过引用传递的。一旦你将它们传递到某个地方,它们可以被修改。

【讨论】:

  • 所以,如果我有一个 Json 对象列表。我想接受用户的一个函数,然后我想将该函数作为整个列表上的地图运行,并在客户端上向用户显示一个新列表,这是他的代码的效果。我如何做到这一点,以确保用户不会写任何会影响除列表项之外的任何其他内容的内容?
  • @AmoghTalpallikar 将您的内容放在任意代码无法访问的范围内。我建议您阅读如何在 JS 中模拟私有作用域,以了解有关保护值的更多信息。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-16
  • 1970-01-01
  • 2015-09-08
  • 2013-02-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多