JavaScript - 在保持私有的同时提取功能 [英] JavaScript - extract out function while keeping it private

查看:69
本文介绍了JavaScript - 在保持私有的同时提取功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前我有这样的结构:

(function(myScope) {
  myScope.public = function() {alert("I'm public!")};
  myScope.privileged = function() {alert("I can call private!"); private();};
  var private = function() {alert("I'm private!")};
})(window.myObj);

一切正常。无法从外界访问 private ,而特权可以调用它。但现在私有部分太大了,我希望将其解压缩出来。我想让它从外部无法访问,但它需要由特权函数调用。有没有办法实现这一目标?

It works fine. private is not accessible from the outside world while privileged can call it. But now the private parts are too big such that I hope to extract it out. I want to keep it inaccessible from the outside but it needs to be invoked by the privileged functions. Is there a way to achieve that?

更新:

以上是只是一个例子。一般的问题是,随着应用程序的扩展,单个js文件变得越来越长且难以管理。目标是将这样的js文件拆分为模块,而不会影响隐私。

The above is just an example. The general problem is that as the app extends, the single js file grows to become long and unmanageable. The goal is to split such js file into module, without compromising privacy.

推荐答案

您需要将代码分解为更小的代码部分。对于每件事,您可能希望使实例引用为local-scoped,但您可以从其他文件中导入类/代码/功能。

You will need to break your code down into smaller parts. For each thing, you might want to make the instance reference local-scoped, but you can import the class/code/functionality from a different file.

炸毁您的示例三个文件:

Blowing up your example to three files:

function makeAlerter(state) {
  return function() {
    alert("I'm "+state);
  };
}

(function(myScope) {
  var private = makeAlerter("private"); // not the whole private coding here
  myScope.privileged = function() { // but the privileged code needs to stay
    alert("I can call private!"); private();
  };
})(window.myObj);

(function(myScope) {
  myScope.public = function() {alert("I'm public!")};
})(window.myObj);

这篇关于JavaScript - 在保持私有的同时提取功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆