关于typescript:TypeScript基础学习4-类

2次阅读

共计 1659 个字符,预计需要花费 5 分钟才能阅读完成。

es5 的办法

最简略的类

 function Person() {
   this.name = 'zy'
   this.age = 27
      this.run = function () {console.log( `${this.name} is run`)  // zy is run
   }
 }
 let person = new Person()
 person.sex = 'female'
 console.log('person.name', person.name) // zy
 console.log('person.sex', person.sex) // female

原型链外面减少属性和办法

   Person.prototype.grade = '一年级'
   Person.prototype.work = function () {console.log( `${this.name} is work`)  // zy is work
   }
  console.log('person.grade', person.grade) // 一年级
  person.work()

增加静态方法

  Person.getInfo = function () {console.log('person.getInfo') // person.getInfo
    }
  Person.getInfo()

继承


1. 对象假冒继承形式,只能继承【构造函数】里的属性和办法
  function Web () {Person.call(this) // 
  }
  let web = new Web()
  console.log('Web.name', web.name) //  zy
  console.log('Web.grade', web.grade) // undefined

2. 原型链继承形式,能继承【构造函数】和【原型链】上的属性和办法
   不能传参调用
  function Web () {}
  Web.prototype =  new Person()
  let web = new Web()
  console.log('Web.name', web.name) // zy
  console.log('Web.grade', web.grade) // 一年级
3. 对象假冒 + 原型链继承形式
 function Person(name, age) {
      this.name = name
      this.age = age
      this.run = function () {console.log( `${this.name} is run`)  // zy is run
      }
    }
    function Web(name, age) {Person.call(this, name, age) // 继承构造函数的属性和办法
    }
    Web.prototype = Person.prototype // 继承原型链的属性和办法
    let web = new Web('zy', 27)
    web.run()

es6 的办法

最根底的类

class Person {
    name: string; // 属性,后面省略了 public 关键字
    constructor (n:string) { // 构造函数,实例化类的时候触发的函数
        this.name = n
    } 
    run ():void {console.log(`${this.name} is run`) // zy is run
    }
} 
let person = new Person('zy')
person.run()

继承

class Person {
    name: string; // 属性,后面省略了 public 关键字
    constructor (name:string) { // 构造函数,实例化类的时候触发的函数
        this.name = name
    } 
    run ():void {console.log(`${this.name} is run`) // ying is run
    }
} 


class Web extends  Person{constructor (name:string) {super(name) // 初始化父类的构造函数
    }
}
let web = new Web('ying')
web.run()

类外面的修饰符

public 私有 在类外面、子类、类里面都能够拜访
protected 爱护类型 在类外面、子类外面能够拜访,在类内部没法拜访
privated 公有 在类外面能够拜访 子类、类里面不能够拜访

正文完
 0