Skip to main content
 首页 » 编程设计

javascript之如何使用 ES6 类在 AngularJS Controller 中保持注入(inject)的依赖项私有(private)

2025年05月04日99kuangbin

我知道我的问题与 this post 有关,但我想知道是否有特定于 AngularJS 的方法来解决这个问题。

这是交易:

我在我的 Angular 指令中使用 ES6 Class 和 ControllerAs,所以 Controller 声明如下:

class myCtrl { 
  constructor ( $log ) { 
    'ngInject'; 
 
    // Dependency Injections 
    var privateLog  = $log;      // Private but scoped to constructor 
    this.publicLog  = $log;      // Public 
 
    // Default attributes 
    this.foo = 'bar'; 
 
    this.publicLog.log('it works in constructor');  // logs 'it works in constructor' 
    privateLog.log('it works in constructor');      // logs 'it works in constructor' 
  } 
 
  logSomething () { 
    this.publicLog.log('it works in class method'); // logs 'it works in class method' 
    try { 
      privateLog.log('it works in class method'); 
    } 
    catch(e) { 
      console.log(e);                               // Uncaught ReferenceError: privateLog is not defined 
    } 
  } 
} 
 
var test = new myCtrl(); 
 
test.logSomething(); 
test.publicLog.log('is public');      // logs 'is public'  
try { 
  test.privateLog.log('is private'); 
} 
catch(e) { 
  console.log(e);                     // Uncaught TypeError: Cannot read property 'log' of undefined 
} 

问题是我想在所有类方法中访问我的依赖注入(inject), 但我不希望它们可以从外部公开访问。

此外,我不想在构造函数中声明我的方法,因为我不想为每个实例重新声明它们。

是否有正确的方法来执行此操作,还是我遗漏了什么?

Here is the Fiddle

请您参考如下方法:

如果你想保持注入(inject)器的私密性,使用经典的 Angular Controller 结构,就像这样

function MyCtrl($log) { 
   'ngInject'; 
   this.logSomething = function(message) { 
       $log(message); 
   } 
} 

现在实际的 $log 隐藏在闭包中,但是 logSomething 对模板公开可用。

UPD。如果你出于某种原因想继续使用 ES6 类,你可以尝试使用任何现有的方法将一些类成员设为私有(private)。有 a review可能的方法。