如何使用Traceur在ES6类中实现私有方法 [英] How to implement private method in ES6 class with Traceur

查看:125
本文介绍了如何使用Traceur在ES6类中实现私有方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我现在使用Traceur Compiler具有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 关键字(来自和谐)。而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.

那么,是否有可能使用与traceur编译器兼容的ES6类中的私有数据? p>

So, is there any possibility to use private data in ES6 class compatible with traceur compiler?

推荐答案

没有 private public protected 当前 ECMAScript 6中的关键字规范

所以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> here )。另一个选择是 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是目前最好的解决方案 - 只需使用伪隐私。如果您经常使用应用调用与您的方法,那么这种方法是非常具体的对象。所以值得在你的班级中用下划线前缀来声明:

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

这篇关于如何使用Traceur在ES6类中实现私有方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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