如何在ES6类中声明本地函数?

时间:2015-11-17 15:00:48

标签: javascript class ecmascript-6

我有一个只能在类中使用的函数,并且不希望它在类外可以访问。

class Auth {
  /*@ngInject*/
  constructor($http, $cookies, $q, User) {
    this.$http = $http;
    this.$cookies = $cookies;
    this.$q = $q;
    this.User = User;

    localFunc(); // Need to create this function, and need it to be accessible only inside this class
  }
}

到目前为止我所做的是宣布课外的功能

function localFunc() {
  return 'foo';
}
class Auth {
  ...
}

然而,这不好,因为它污染了全局功能,除了我把它包裹在IIFE中。那么,有什么方法可以在ES6类中创建一个本地函数吗?

2 个答案:

答案 0 :(得分:13)

不,无法在class中声明本地函数。您当然可以使用下划线前缀声明(静态)辅助方法并将它们标记为“私有”,但这可能不是您想要的。而且你总是可以在方法中声明局部函数。

但如果您需要多次,那么唯一的方法就是将它放在class旁边。如果您正在编写脚本,则需要像往常一样使用IEFE。如果您正在编写ES6模块(这是首选解决方案),隐私是微不足道的:只是不要export该功能。

答案 1 :(得分:0)

您可以使用符号:

const localFunc = Symbol();
class Auth {
  /*@ngInject*/
  constructor($http, $cookies, $q, User) {
    this.$http = $http;
    this.$cookies = $cookies;
    this.$q = $q;
    this.User = User;

    this[localFunc] = function() {
      // I am private
    };
  }
}
相关问题