如何在ES6类中声明局部函数? [英] How to declare local function inside ES6 class?

查看:268
本文介绍了如何在ES6类中声明局部函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a function that can be used only inside a class and don't want it to be accessible outside the 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
  }
}

到目前为止,我所做的是在类之外声明函数

What I have done so far is declaring the function outside the class

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

然而,这不好,因为它污染全局函数,除了我包装在IIFE。所以,是不是我能在ES6类中创建一个局部函数?

However, this's not good as it pollutes the global function, except I wrapped it inside IIFE. So, is there somehow I can create a local function inside a ES6 class?

推荐答案

函数在中。你当然可以声明(静态)辅助方法,并使用下划线前缀将它们标记为私有,但这可能不是你想要的。你可以在一个方法中声明局部函数。

No, there is no way to declare local functions in a class. You can of course declare (static) helper methods and mark them as "private" using underscore prefixes, but that's probably not what you want. And you can always declare the local function inside of a method.

但是如果你需要它多次,那么唯一的方法是把它放在 class 。如果你正在写一个脚本,IEFE将像往常一样必要。如果你正在写一个ES6模块(这是首选的解决方案),隐私是微不足道:只是不要导出的功能。

But if you need it multiple times then the only way to go is to place it next to the class. If you are writing a script, an IEFE will be necessary as usual. If you're writing an ES6 module (which is the preferred solution), privacy is trivial: just don't export the function.

这篇关于如何在ES6类中声明局部函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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