TypeScript入门-类
▓▓▓▓▓▓ 大致介绍
在ECMASript6中引入了类这一概念,通过class声明一个类。对于学习过C和C++的人应该不会陌生
▓▓▓▓▓▓ 类
看一个简单的类:
class Greeter {
greeting: string;
constructor(message: string){
this.greeting = message;
};
greet(){
return "Hello, " + this.greeting;
}
}
let greeter = new Greeter('world');
在上面的例子中,利用class关键字声明了一个类Greeter,在类中,定义了一个属性,一个构造函数和一个方法
▓▓▓▓▓▓ 继承
类通常都是用来继承的,但是Typescript中的继承和C中的继承还是有点差别的
例如:
class Animal {
name:string;
constructor(theName: string) { this.name = theName; }
move(distanceInMeters: number = 0) {
console.log(`${this.name} moved ${distanceInMeters}m.`);
}
}
class Snake extends Animal {
constructor(name: string) { super(name); }
move(distanceInMeters = 5) {
console.log("Slithering...");
super.move(distanceInMeters);
}
}
class Horse extends Animal {
constructor(name: string) { super(name); }
move(distanceInMeters = 45) {
console.log("Galloping...");
super.move(distanceInMeters);
}
}
let sam = new Snake("Sammy the Python");
let tom: Animal = new Horse("Tommy the Palomino");
sam.move();
tom.move(34);
首先定义了一个类Animal,之后利用关键字extends定义了一个继承Animal的类Snake,可以发现在Snake的构造函数里使用了super()方法,这是因为包含constructor函数的派生类必须调用super(),它会执行基类的构造方法。
在继承类中重写了构造函数,super.move()是继承父类的方法
▓▓▓▓▓▓ public、private和protected
这三个概念对于学习过C的人应该很容易理解
public:公开的,在类外也是可以访问的
之前写的类中都是默认为public
class Animal {
public name: string;
public constructor(theName: string) { this.name = theName; }
public move(distanceInMeters: number) {
console.log(`${this.name} moved ${distanceInMeters}m.`);
}
}
private:私有的,只有在该类中可以访问,在继承类中都不可访问
class Animal {
private name: string;
public constructor(message: string){
this.name = message;
}
}
let animal = new Animal('cat');
animal.name;//error
protected:保护的,是介于public和private之间的,和private的区别就是在继承类中时可以访问的
class Animal {
private name: string;
protected sex: string;
public constructor(message: string){
this.name = message;
}
}
class Snake extends Animal {
constructor(message){super(message)};
get(){
console.log(this.name); //error
console.log(this.sex);
}
}
在上面的例子中,name是private,在继承类中是不可以访问的,而sex是可以被访问的,当然这两个属性在类外都不可以被访问
注意:如果一个类的构造函数被声明为protected,这意味着这个类不能在包含它的类外被实例化,但是能被继承。
▓▓▓▓▓▓ readonly修饰符
可以用关键字readonly声明属性为只读的,只读属性必须是在声明时或者构造函数里初始化
class Octopus {
readonly name: string;
readonly numberOfLegs: number = 8;
constructor (theName: string) {
this.name = theName;
}
}
let dad = new Octopus("Man with the 8 strong legs");
dad.name = "Man with the 3-piece suit"; // error! name is readonly.
▓▓▓▓▓▓ 参数属性
利用参数属性可以简写很多代码
class Octopus {
name: string;
constructor (theName: string) {
this.name = theName;
}
}
//利用参数属性
class Octopus {
constructor(public name: string){}
}
这两段代码的作用是一样的
▓▓▓▓▓▓ 存取器
TypeScript支持getters/setters来截取对对象成员的访问。 它能帮助你有效的控制对对象成员的访问。
let passcode = "secret passcode";
class Employee {
private _fullName: string;
get fullName(): string {
return this._fullName;
}
set fullName(newName: string) {
if (passcode && passcode == "secret passcode") {
this._fullName = newName;
}
else {
console.log("Error: Unauthorized update of employee!");
}
}
}
let employee = new Employee();
employee.fullName = "Bob Smith";
if (employee.fullName) {
alert(employee.fullName);
}
▓▓▓▓▓▓ 抽象类
抽象类是供其它类继承的基类。 他们一般不会直接被实例化。 不同于接口,抽象类可以包含成员的实现细节。abstract关键字是用于定义抽象类和在抽象类内部定义抽象方法。抽象类中的抽象方法不包含具体实现并且必须在派生类中实现。
abstract class Department {
constructor(public name: string) {
}
printName(): void {
console.log('Department name: ' + this.name);
}
abstract printMeeting(): void; // 必须在派生类中实现
}
class AccountingDepartment extends Department {
constructor() {
super('Accounting and Auditing'); // constructors in derived classes must call super()
}
printMeeting(): void {
console.log('The Accounting Department meets each Monday at 10am.');
}
generateReports(): void {
console.log('Generating accounting reports...');
}
}
let department: Department; // ok to create a reference to an abstract type
department = new Department(); // error: cannot create an instance of an abstract class
department = new AccountingDepartment(); // ok to create and assign a non-abstract subclass
department.printName();
department.printMeeting();
department.generateReports(); // error: method doesn't exist on declared abstract type
参考资料:
TypeScript入门-类的更多相关文章
- TypeScript入门四:TypeScript的类(class)
TypeScript类的基本使用(修饰符) TypeScript类的抽象类(abstract) TypeScript类的高级技巧 一.TypeScript类的基本使用(修饰符) TypeScript的 ...
- TypeScript入门指南(JavaScript的超集)
TypeScript入门指南(JavaScript的超集) 你是否听过 TypeScript? TypeScript 是 JavaScript 的超集,TypeScript结合了类型检查和静态分析 ...
- TypeScript入门实例
前言 TypeScript是JavaScript的超集,微软公司开发,利用es6语法,实现对js的面向对象编程思想,写代码的时候会像强类型语言一样,指定参数类型.返回值类型,类型不对会报错,但编译后还 ...
- typescript 入门教程一
##### 从今天开始,持续更新typescript入门教程系列.... 目前ts越来越火,主流的前端框架,好比*angular,vue 3*均是采用ts来编写,所有很多公司的项目都是用**ts**来 ...
- TypeScript入门五:TypeScript的接口
TypeScript接口的基本使用 TypeScript函数类型接口 TypeScript可索引类型接口 TypeScript类类型接口 TypeScript接口与继承 一.TypeScript接口的 ...
- TypeScript 入门教程学习笔记
TypeScript 入门教程学习笔记 1. 数据类型定义 类型 实例 说明 Number let num: number = 1; 基本类型 String let myName: string = ...
- TypeScript 入门自学笔记 — 类型断言(二)
码文不易,转载请带上本文链接,感谢~ https://www.cnblogs.com/echoyya/p/14558034.html 目录 码文不易,转载请带上本文链接,感谢~ https://www ...
- TypeScript 素描 - 类
本文虽然是学自官方教程而来,但是也融入了自己的理解,而且对官方的例子做了一些修改 /* 类 面向对象编程的一大核心 使用C#.Java进行编程的朋友肯定已经是不能够再熟悉了 TypeScript的类与 ...
- TypeScript入门(三)面向对象特性
一.类(Class) 类是ts的核心,使用ts开发时,大部分代码都是写在类里面. 1.类的声明 多个对象有相同的属性和方法,但是状态不同. 声明类的属性和方法时可以加 访问控制符,作用是:类的属性和方 ...
随机推荐
- krpano之语音介绍
语音介绍:在每进入一个场景时,播放一段该场景的语音介绍. 制作步骤: 1.定义全局事件.在关闭场景时执行stopsounds(),在打开新场景时执行automusic(). <events on ...
- 【转载】C# 从服务器下载文件
支持并尊重原创!原文地址:https://www.cnblogs.com/GoCircle/p/6429136.html 一.//TransmitFile实现下载 protected void But ...
- Winform绑定图片的三种方式
1.绝对路径: this.pictureBox2.Image=Image.FromFile("D:\\001.jpg"); 2.相对路径: Application.StartupP ...
- 【转】教你如何实现linux和W…
原文地址:[转]教你如何实现linux和Windows之间的文件共享,samba的安装与配置作者:铅笔小蜡 本人在虚拟机下装fedora13,已经实现. 1. 首先检查os是否安装好了samba. [ ...
- Bootstrap教程目录
1.Bootstrap 简介(Web前端CSS框架) 2.Bootstrap 学习资料 3.Bootstrap 入门 4.Bootstrap 概览 5.Bootstrap 栅格系统 6.Bootstr ...
- MFC小程序
1.将菜单栏归零,工具栏放在窗口低部,加载自己新建的工具栏 CMainFrame::OnCreate()函数中 this->SetMenu(0); 2.将窗口初始化为最大化 APP类中:m_pM ...
- Tornado之自定义session
面向对象基础 面向对象中通过索引的方式访问对象,需要内部实现 __getitem__ .__delitem__.__setitem__方法 #!/usr/bin/env python # -*- ...
- Django框架 之 querySet详解
Django框架 之 querySet详解 浏览目录 可切片 可迭代 惰性查询 缓存机制 exists()与iterator()方法 QuerySet 可切片 使用Python 的切片语法来限制查询集 ...
- Git安装和常用命令
Git是目前世界上最先进的分布式版本控制系统!!! Git能自动帮我们记录每次文件的改动,还可以让同事协作编辑. 接下来,简单的介绍下Git的安装和常用命令: Git安装: 1.Windows系统,进 ...
- 【2008nmj】GDA二元分类.docx