在打字稿

时间:2017-04-12 15:15:59

标签: javascript angularjs typescript

这是英雄教程角度之旅的app.component.ts

import { Component } from '@angular/core';

export class Hero{
 name : string;
 id : number;
}

const HEROES : Hero[] = [
    {name : 'jhon snow', id : 1},
    {name : 'wiz kahlifa',id : 2},
    {name : 'superman',id : 3},
    {name : 'batman',id : 4},
    {name : 'supersyian', id : 5}
];

我想知道类如何在类型脚本中工作我检查了app.component.js并看到了以下代码行

var Hero = (function () {
 function Hero() {
 }
 return Hero;
}());
exports.Hero = Hero;
var HEROES = [
 { name: 'jhon snow', id: 1 },
 { name: 'wiz kahlifa', id: 2 },
 { name: 'superman', id: 3 },
 { name: 'batman', id: 4 },
 { name: 'supersyian', id: 5 }
];

我无法理解app.component.js中类的使用,HEROES数组和我在app.component.ts中创建的Hero类之间没有链接

2 个答案:

答案 0 :(得分:1)

  

我无法理解app.component.js中的类的使用HEROES数组与我在app.component.ts中创建的英雄类之间没有链接

你是对的。这应该。我建议不要专注于旧浏览器的编译代码。您可以编译现代JavaScript引擎:关键字class将保留,您的问题仍然存在。

以下代码声明了一个ES6类(使用TypeScript语法糖):

export class Hero {
  name: string;
  id: number;
}

然后,实例化该类的唯一方法是使用new运算符:

  

但是,您只能通过newsource: exploringjs from Dr. Axel Rauschmayer

调用课程

以下代码误导性

const HEROES : Hero[] = [
  {name : 'jhon snow', id : 1},
  {name : 'wiz kahlifa',id : 2},
  // ...
];

它声明了一个类型为Hero[]的数组。但是构造函数没有被执行。它充满了不属于该类实例的对象。

有效方式

使用界面:

export interface Hero {
  name: string;
  id: number;
}
const HEROES : Hero[] = [
  {name : 'jhon snow', id : 1},
  {name : 'wiz kahlifa', id : 2},
  // ...
];

上课:

export class Hero {
  constructor (public name: string, public id: number) {
  }
}
const HEROES : Hero[] = [
  new Hero('jhon snow', 1),
  new Hero('wiz kahlifa', 2),
  // ...
];

答案 1 :(得分:0)

所以这里的Transpiler将Type脚本类转换为javascript 5或ES5兼容代码。在ES5中,在定义使用函数语法的“类”时,不使用类语法。例如

function car() { } //This defines a "class" called car but it doesnt do anything yet

//This defines a function of car that returns the max speed
car.prototype.maxSpeed = function() {
 return "70 MPH";
}

如您所见,此处没有类型,因为javascript是动态类型的。声明类后,无需声明任何内容。

在您的示例中,您没有看到Name和ID,因为它们用于在typescript中进行编译时错误检查。它们不会存在于他们的javascript语言中。

至于你的常英雄。这些只是javascript对象,它们在实例化之后采用你的类将在javascript中采用的形状。