- // js实现继承
- // 父类
- function Father(name) {
- this.name = name
- this.say = function () {
- console.log(this.name + "在唱歌")
- }
- }
- var f = new Father("逍遥的码农")
-
- // 子类
- function Son(name) {
- Father.call(this, name)
- }
- Son.prototype = Father.prototype
- var s = new Son("张三")
- s.say()
- // ts class类实现继承
- // ts父类
- class TsFather {
- name: string
- // 构造函数
- constructor(name: string) {
- this.name = name
-
- }
- say(): void {
- console.log(this.name + "在唱歌")
- }
- }
- var tsf = new TsFather("逍遥的码农")
-
- // ts子类
- class TsSon extends TsFather {
- constructor(name: string) {
- super(name)
- }
- }
- var tss = new TsSon("张三")
- tss.say()
(1)public:公有,在类里面、子类、类外面都可以访问(默认的就不做演示)
(2)protected:保护类型,在雷里面、子类里面可以访问,在类外部不能访问
(3)private:私有,在类里面可以访问,子类、类外边不能访问
protected:
- class A {
- protected name: string
- constructor(name: string) {
- this.name = name
- }
- }
- var a = new A("张三")
- console.log(a.name) //属性“name”受保护,只能在类“A”及其子类中访问。
private:
- class A {
- private name: string
- constructor(name: string) {
- this.name = name
- }
- }
- var a = new A("张三")
- class B extends A{
- constructor(name:string){
- super(name)
-
- }
- say():void{
- console.log(this.name) //属性“name”为私有属性,只能在类“A”中访问。
- }
- }
- var b = new B("李四")
- b.say()