风雨砥砺,岁月如歌——Ts之类的继承和“super”关键字的用法

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Baronrothschlid/article/details/82562382

小编初接触ts,真的越来越感到欣喜,当初学js的时间真的感觉很懵逼,现在学习ts竟然有一种豁然开朗的感觉,个人觉得ts在逻辑和语法上更加的清晰明了,先奉上一段ts代码:

class Person{

	constructor(public name: string) {
		console.log("I am a boy.");
	}
	eat() {
		console.log("I can eat.");
	}
}

//继承Person的子类
class boy extends Person{

	//子类添加新的构造函数,需要引用父类的构造函数
	constructor(name: string, id: string) {
		super(name);//super关键字的用法1,引用父类的构造函数
		this.id = id;
		console.log("My id is "+this.id+".  My name is "+this.name+".");//为了使排版更美观
}
	id: any;
	work() {
		super.eat();	//super关键字的用法2,调用父类的方法
		this.dowork();
	}
	//创建受保护的方法,使其在类外部不能被调用,达到必须先吃饭再学习的流程
	private dowork() { 
		console.log("I can learn well.")
	}
}
var boy1 = new boy("Baron","666")
boy1.work();

同样的功能的js代码,童鞋们可以用心稍微感受一下:

var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    }
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var Person = /** @class */ (function () {
    function Person(name) {
        this.name = name;
        console.log("I am a boy.");
    }
    Person.prototype.eat = function () {
        console.log("I can eat.");
    };
    return Person;
}());
//继承Person的子类
var boy = /** @class */ (function (_super) {
    __extends(boy, _super);
    //子类添加新的构造函数,需要引用父类的构造函数
    function boy(name, id) {
        var _this = _super.call(this, name) || this;
        _this.id = id;
        console.log("My id is " + _this.id + ".  My name is " + _this.name + "."); //为了使排版更美观
        return _this;
    }
    boy.prototype.work = function () {
        _super.prototype.eat.call(this); //super关键字的用法2,调用父类的方法
        this.dowork();
    };
    //创建受保护的方法,使其在类外部不能被调用,达到必须先吃饭再学习的流程
    boy.prototype.dowork = function () {
        console.log("I can learn well.");
    };
    return boy;
}(Person));
var boy1 = new boy("Baron", "666");
boy1.work();

我们想要达到的效果:

在此需要划重点的是:

1、子类在创建新的构造函数的时间必须引用父类的构造函数,可以采用“super”关键字。

2、子类的方法可以采用“super”关键字调用父类的方法。

3、某些需要加以限制的方法可以采用访问修饰符加以限制。

感谢阅读!

猜你喜欢

转载自blog.csdn.net/Baronrothschlid/article/details/82562382
今日推荐