TypeScript 类 中的无变量变量是什么意思?

What do var-less variables mean within TypeScript classes?

在 Angular2 中创建组件时 class。为什么我们不需要 var?什么时候声明一个新变量?例如:

@Component({
  selector: 'my-app',
  template: `
    <h1>{{title}}</h1>
    `
})
export class AppComponent {
  title = 'My title';
}

怎么不是var title = 'My title';呢?

编辑:我最初的问题是在阅读 this 时出现的,原始代码如下所示:

import { Component } from '@angular/core';
export class Hero {
  id: number;
  name: string;
}
@Component({
  selector: 'my-app',
  template: `
    <h1>{{title}}</h1>
    <h2>{{hero.name}} details!</h2>
    <div><label>id: </label>{{hero.id}}</div>
    <div>
      <label>name: </label>
      <input [(ngModel)]="hero.name" placeholder="name">
    </div>
    `
})
export class AppComponent {
  title = 'Tour of Heroes';
  hero: Hero = {
    id: 1,
    name: 'Windstorm'
  };
}

这是一个 TypeScript(并提出了 ES2015)shorthand 糖,用于为 AppComponent 对象类型设置实例变量。这些不同于 JavaScript 中的实际作用域变量。

目前此功能处于 ES2015 的提案阶段。然而,由于 TypeScript 是它自己的语言,它是 ES 的严格超集,它实现了大部分提议的 ESnext 标准。将此与 Babel 一起使用的警告是您需要包含 stage-1 插件(或使用包含此特定 ES 提议的不同转译器)。但由于这只是一个提案,所以它不是 TypeScript 之外的标准。

此示例的 vanilla JavaScript counterpart 转换为:

function AppComponent() {
  this.title = 'Tour of Heroes';
  this.hero = 'Windstorm';
}

var appComponent = new AppComponent();
console.log(appComponent);
console.log(appComponent.title);
console.log(appComponent.hero);

注意: 由于 Angular2 传统上使用 TypeScript,因此如果您选择使用 TypeScript 而不是替代品,那么手边 online transpiler 会很有帮助。