如何实现私有方法在ES6类与Traceur [英] How to implement private method in ES6 class with Traceur
问题描述
我使用Traceur编译器来优化ES6功能。
I use Traceur Compiler to have advantage with ES6 features now.
我想从ES5实现这个东西:
I want to implement this stuff from ES5:
function Animal() {
var self = this,
sayHi;
sayHi = function() {
self.hi();
};
this.hi = function() {/* ... */}
}
目前,traceur不支持 private
和 public
关键字( from和谐)。和ES6类语法不允许在类体中使用简单的 var
(或 let
)语句。
Currently traceur does not support private
and public
keywords (from harmony). And ES6 class syntax does not allow to use simple var
(or let
) statements in class body.
我发现的唯一方法是在类声明之前模拟privates。像:
The only way that I am find is to simulate privates before class declaration. Something like:
var sayHi = function() {
// ... do stuff
};
class Animal {
...
那么没有什么,但预期你不能传递正确的这到私人方法没有
应用
-ing或
It is better then nothing but as expected you can not pass correct this
to private method without apply
-ing or bind
-ing it every time.
那么,有没有可能使用ES6类中的私有数据与traceur编译器兼容?
So, is there any possibility to use private data in ES6 class compatible with traceur compiler?
推荐答案
没有私人
, code>或
保护的
关键字在当前的 ECMAScript 6规范。
There are no private
, public
or protected
keywords in current ECMAScript 6 specification.
因此,Traceur不支持 private
和 public
。 6to5(目前称为Babel)实现此提案用于实验目的(另请参阅本讨论)。
So Traceur does not support private
and public
. 6to5 (currently it's called "Babel") realizes this proposal for experimental purpose (see also this discussion). But it's just proposal, after all.
现在你可以通过 WeakMap
模拟私有属性a href =https://curiosity-driven.org/private-properties-in-javascript>此处)。另一个选择是 Symbol
- 但它并不意味着任何隐私,因为属性很容易通过 Object.getOwnPropertySymbols
获得。
So for now you can just simulate private properties through WeakMap
(see here). Another alternative is Symbol
- but it doesn't imply any privacy as property easily can be got through Object.getOwnPropertySymbols
.
IMHO这时的最佳解决方案 - 只需使用伪隐私。如果你的方法经常使用 apply
或调用
,那么这个方法是非常具体的对象。因此,值得在类中使用下划线前缀来声明它:
IMHO the best solution at this time - just use pseudo privacy. If you frequently use apply
or call
with your method, then this method is very object specific. So it's worth to declare it in your class just with underscore prefix:
class Animal {
_sayHi() {
// do stuff
}
}
这篇关于如何实现私有方法在ES6类与Traceur的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!