ES6类的私有成员语法 [英] ES6 classes private member syntax
本文介绍了ES6类的私有成员语法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个快速问题。
换句话说,如何实现
In other words, how to implement
function MyClass () {
var privateFunction = function () {
return 0;
};
this.publicFunction = function () {
return 1;
};
}
为
class MyClass {
// ???
publicFunction () {
return 1;
}
}
推荐答案
类别没有太大不同。构造函数的主体简单地成为构造函数的主体
:
It's not much different for classes. The body of the constructor function simply becomes the body of constructor
:
class MyClass {
constructor() {
var privateFunction = function () {
return 0;
};
this.publicFunction = function () {
return 1;
};
}
}
当然 publicFunction
也可以是一个真正的方法,如在你的例子中,如果它不需要访问
privateFunction
。
我不是特别建议这样做(我反对伪私有属性的各种原因),但这将是你的代码的最直接的翻译。
I'm not particularily advising to do this (I'm against pseudo privat properties for various reasons), but that would be the most straightforward translation of your code.
这篇关于ES6类的私有成员语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文