5

我正在尝试让 Aurelia 的入门应用程序正常工作,但我在第一页就遇到了错误。 http://aurelia.io/get-started.html

有问题的代码:

export class Welcome {
  heading = 'Welcome to the Aurelia Navigation App!';
  firstName = 'John';
  lastName = 'Doe';

  get fullName(){
    return `${this.firstName} ${this.lastName}`;
  }

  welcome(){
    alert(`Welcome, ${this.fullName}!`);
  }
}

错误 :

    [21:46:19] Plumber found unhandled error:
 SyntaxError in plugin 'gulp-babel'
Message:
    D:/workspace/aurelia/navigation-app/src/app.js: Unexpected token (2:10)
  1 | export class Welcome {
> 2 |   heading = 'Welcome to the Aurelia Navigation App!';
    |           ^
  3 |   firstName = 'John';
  4 |   lastName = 'Doe';
  5 |
[21:46:19] Finished 'build-system' after 20 ms

我不得不说我在windows上,它可能会造成一些麻烦。


我通过将变量放在构造函数中“解决”了这个问题。但是上面的语法不是有效的 ES6 吗?是 ES7 还是什么还不能用?


我知道这段代码看起来很奇怪但我不是作者,它是来自 Aurelia 教程的原始代码

4

2 回答 2

11

以下语法对于类不是有效的 ES6 语法。但是,它是类的有效 ES7 属性初始值设定项语法。要使用它,如果您使用的是 Babel,则需要确保专门启用此功能。这在 Aurelia 博客中有记录,它被配置为最新骨架的一部分。

export class Welcome {
  heading = 'Welcome to the Aurelia Navigation App!';
  firstName = 'John';
  lastName = 'Doe';

  get fullName(){
    return `${this.firstName} ${this.lastName}`;
  }

  welcome(){
    alert(`Welcome, ${this.fullName}!`);
  }
}
于 2015-04-14T19:53:45.083 回答
1

但是上面的语法不是有效的 ES6 吗?

不它不是。类主体只能包含方法定义。不过,它似乎在 Babel 的实验模式下工作。

我通过将变量放在构造函数中“解决”了这个问题。

这是正确的解决方案。数据属性通常应该是实例属性。如果你想把它们放在原型上,你必须在 ES6 中明确地这样做:

export class Welcome {
  constructor() {
    this.firstName = 'John';
    this.lastName = 'Doe';
  }

  get fullName(){
    return `${this.firstName} ${this.lastName}`;
  }

  welcome(){
    alert(`Welcome, ${this.fullName}!`);
  }
}
Welcom.prototype.heading = 'Welcome to the Aurelia Navigation App!';
于 2015-04-14T15:36:09.227 回答