2016-03-21 109 views
0

我见过的成员变量在ES6声明如下声明成员变量的

export class MyClass 
{ 
    x = null; 

    constructor() { 
     this.x = 1; 
    } 

    write() { 
     console.log(this.x); 
    } 
} 

和巴贝尔似乎罚款transpile它。

这是一种声明成员变量的有效方法吗?

+1

JS中没有“成员变量”这样的东西。你所看到的不是ES6,而是ES8的一个实验性功能提案。不要使用它。 – Bergi

回答

2

这是ES Class Fields & Static Properties的建议的一部分。 它支持babeljs,与此plugin。 这是一个babel stage-1插件,所以如果你使用的是stage-1或者stage-0,这是支持的。

+0

谢谢!我不知道那件事 –

2

我不相信这是正确的。至少,MDN没有提及任何这样的语法。

至于你的例子,让我们逐行解决它。

class MyClass { // Class declaration, all good here 
    x = null; // I assume you're telling javascript that the variable x exists? 

    constructor() { 
     this.x = 1; // You do that here just fine. 
    } 

    write() { 
     console.log(this.x); // And here we use the variable, after the constructor ran 
    } 
} 

我在单独声明成员变量时看不到任何值。你在构造函数中创建它。这应该是所有你需要的