gpt4 book ai didi

javascript - typescript中的类有什么用

转载 作者:太空宇宙 更新时间:2023-11-04 15:48:17 26 4
gpt4 key购买 nike

这是英雄教程的 Angular Tour 的 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 类之间没有链接

最佳答案

I am not able to understand the use of class as in the app.component.js there is no link between the HEROES array and the Hero class i created in app.component.ts

你是对的。它应该。我建议不要关注旧浏览器的编译代码。您可以针对现代 JavaScript 引擎进行编译:关键字 class 将保留,您的问题也将保留。

以下代码声明一个 ES6 类(带有 TypeScript 语法糖):

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

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

However, you can only invoke a class via new (source: exploringjs from Dr. Axel Rauschmayer)

以下代码具有误导性:

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

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

有效方法

带有接口(interface):

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),
// ...
];

关于javascript - typescript中的类有什么用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43373534/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com