我怎样才能运行有限的function访问的JavaScript代码

我想加载一个JavaScript文件作为特定任务的脚本,它应该只能通过我定义的特定function访问。

我不想让编写代码的人访问像process或某个全局函数这样的全局对象。

我只希望用户使用我为他们准备的函数或对象,而且应该允许他们定义他们自己的函数和variables,而其他的则是不允许的。

有一些包可以做到吗?

例如:

 process; // should be undefined getProcessInfo(); // the function that I prepared for them var process = 0; // should be ok 

您可以使用JavaScript的揭示模块模式,如下所示:

 var Exposer = (function() { var privateVariable = 10; var privateMethod = function() { console.log('Inside a private method!'); privateVariable++; } var methodToExpose = function() { console.log('This is a method I want to expose!'); } var otherMethodIWantToExpose = function() { privateMethod(); } return { first: methodToExpose, second: otherMethodIWantToExpose }; })(); Exposer.first(); // Output: This is a method I want to expose! Exposer.second(); // Output: Inside a private method! Exposer.methodToExpose; // undefined