是否可以在ES6类中创建私有属性?
这是一个例子.我怎样才能阻止访问instance.property?
class Something {
constructor(){
this.property = "test";
}
}
var instance = new Something();
console.log(instance.property); //=> "test"
Run Code Online (Sandbox Code Playgroud) 我现在使用Traceur Compiler来获得ES6功能.
我想从ES5实现这些东西:
function Animal() {
var self = this,
sayHi;
sayHi = function() {
self.hi();
};
this.hi = function() {/* ... */}
}
Run Code Online (Sandbox Code Playgroud)
目前traceur不支持private和public关键字(来自和谐).ES6类语法不允许在类体中使用简单var(或let)语句.
我找到的唯一方法是在类声明之前模拟私有.就像是:
var sayHi = function() {
// ... do stuff
};
class Animal {
...
Run Code Online (Sandbox Code Playgroud)
没有什么比通过预期的更好,this没有apply-ing或bind-ing它每次都不能将正确的方法传递给私有方法.
那么,是否有可能在ES6类中使用与traceur编译器兼容的私有数据?