1、安装nodejs和vscode:nodejs : https://nodejs.org/en/Visual Studio Code : https://www.visualstudio.com/en-us/products/code-vs.aspx安装是很简单的,一 ...
1、安装nodejs和vscode:
nodejs : https://nodejs.org/en/
Visual Studio Code : https://www.visualstudio.com/en-us/products/code-vs.aspx
安装是很简单的,一路next就行,此处不详细描述。
检验node是否安装成功,打开命令行,输入node -v, 显示如下图,说明安装成功。
PS: TypeScript毕竟是微软发明的,用微软的编辑器更省心,当然不是必须的,否则得根据你的编辑器找typescript插件,你懂的。
2、上面的步骤完成后,安装typescript,找开命令行,输入指令:npm install -g typescript
安装完成,命令行输入tsc -v进行检验,显示版本号说明安装成功,如下图
3、完成了typescript环境的配置,接下来我们可以开始写代码了。
新建一个文件夹demo, 在它下面创建oop.ts
oop.ts代码如下:
/** * 声明抽象类Shape * */abstract class Shape { //声明受保护的属性edge, 是的,你没看错,protected只能用于父类和子类 protected edge: number; //声明构造函数,入参类型为number constructor(edge: number) { this.edge = edge; } //声明类实例方法,方法名后面的number是限制方法的返回类型 getEdge(): number { return this.edge; } //声明抽象方法 abstract getArea(): number;}/** * 声明类Triangle, 继承自抽象类Shape,必须实现抽象方法getArea() * */class Triangle extends Shape { //声明类私有属性,其他类不能访问,包括父类 private width: number; private height: number; //声明构造函数,必须显式调用父类构造函数,用super() constructor(width: number, height: number) { super(3); this.width = width; this.height = height; } //实例方法,重写父类同名方法 getArea(): number { return this.width * this.height / 2; }}/** * 声明类Rectangle, 继承自抽象类Shape,必须实现抽象方法getArea() * */class Rectangle extends Shape { //声明类私有属性,其他类不能访问,包括父类 private width: number; private height: number; //声明构造函数,必须显式调用父类构造函数,用super() constructor(width: number, height: number) { super(4); this.width = width; this.height = height; } //实例方法,重写父类同名方法 getArea(): number { return this.width * this.height; }}//模拟入参数类型限制为Shape抽象类实例function outputShape(shape: Shape) { console.log(shape.getEdge()); console.log(shape.getArea());}//模拟程序主入口函数function main() { outputShape(new Triangle(4, 5)); outputShape(new Rectangle(4, 5));}main();
原标题:TypeScript之面向对象初体验
关键词:面向对象
*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们:
admin#shaoqun.com
(#换成@)。