簡體   English   中英

如何在ES6類中聲明本地函數?

[英]How to declare local function inside ES6 class?

我有一個只能在類中使用的函數,並且不希望它在類外部可訪問。

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類中創建一個本地函數嗎?

不,沒有辦法在class聲明局部函數。 您當然可以使用下划線前綴聲明(靜態)輔助方法並將它們標記為“私有”,但這可能不是您想要的。 並且您始終可以在方法內聲明本地函數。

但如果您需要多次,那么唯一的方法就是將它放在class旁邊。 如果您正在編寫腳本,則需要像往常一樣使用IEFE。 如果您正在編寫ES6模塊(這是首選解決方案),隱私是微不足道的:只是不要export該功能。

您可以使用符號:

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
    };
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM