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

查看:16
本文介绍了如何使用 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 不支持 privatepublic 关键字(来自和谐).并且 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.

我发现的唯一方法是在类声明之前模拟私有.类似的东西:

The only way that I am find is to simulate privates before class declaration. Something like:

var sayHi = function() {
    // ... do stuff
};

class Animal {
...

如果没有 apply-ing 或 bind-ing 的话,就不能将正确的 this 传递给私有方法.每次.

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 类中使用私有数据?

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

推荐答案

当前 privatepublicprotected 关键字不存在a href="https://people.mozilla.org/~jorendorff/es6-draft.html" rel="noreferrer">ECMAScript 6 规范.

There are no private, public or protected keywords in current ECMAScript 6 specification.

所以 Traceur 不支持 privatepublic.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 模拟私有属性(见 此处).另一种选择是 Symbol - 但它不提供实际隐私,因为可以通过 Object.getOwnPropertySymbols 轻松访问该属性.

So for now you can just simulate private properties through WeakMap (see here). Another alternative is Symbol - but it doesn't provide actual privacy as the property can be easily accessed through Object.getOwnPropertySymbols.

恕我直言,这是目前最好的解决方案 - 只需使用伪隐私.如果你经常在你的方法中使用 applycall,那么这个方法是非常特定于对象的.所以值得在你的类中用下划线前缀声明它:

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天全站免登陆