类与继承

ES5中:

function People(name,age,number){
  this.name = name
  this.age = age //实例属性
  People.number = number //静态属性
}
//实例方法
People.prototype.showName = function(){
  console.log('我的名字是'+this.name)  
} 
//静态方法
People.getNumber = function(){
  return '666'
}

function Student(name,age,major){
  People.call(this,name,age)     //继承属性
  this.major = major
}
Student.prototype = new People()
Student.prototype.constructor = Student   //继承方法

ES6中:

class People{
  constructor(name,age){
    this.name = name
    this.age = age
    this._sex = -1 //引入_sex的原因的为了避免在set中造成死循环
  }
  //当获取属性的时候涉及到业务逻辑操作,可利用get set(可继承)
  get sex(){
    if(this._sex === 0){
      return 'famale'
    }else if(this._sex === 1){
      return 'male'
    }else{
      return new Error('输入错误')
    }
  }
  set sex(value){
    if(value === 0 || value === 1){
      this._sex = value
    }
  }
  showName(){
    console.log('我的名字是'+ this.name)
  }
  //静态方法,可继承(不能用static定义静态属性)
  static getCount(){
    return 'xx'
  }
}

const p = new People('zs',18)
p.showName()
p.sex = 1
console.log(p.sex)
console.log(People.getCount())

class Student extends People{
  constructor(name,age,major){
    super(name,age)
    this.major = major
  }
}
const s = new Student('ls',22,'code')
console.log(s.name,s.age,s.major)
s.showName()
s.sex = 0
console.log(s.sex)
console.log(Student.getCount())

 

上一篇:python之字符格式化


下一篇:Kotlin Android开发·开始面向对象