ES6语法(三)

1.ES5与ES6声明类比较

  • ES5中声明一个类
let Animal = function(type){
  this.type = type
}
Animal.prototype.eat = function(){
  console.log("eat eat eat")
}
let cat = new Animal("cat")
let dog = new Animal("dog")

console.log(cat)
console.log(dog)

在这里插入图片描述

  • ES6中声明一个类
class Animal{
  constructor(type){
    this.type = type
  }
  eat (){
    console.log("eat eat eat")
  }
}

let cat = new Animal("cat")
let dog = new Animal("dog") 

console.log(cat)
console.log(dog)

在这里插入图片描述
从上面可以看出在ES6中心增加了一个class关键字来定义类,较ES5更加简便,但从上面两张图来看ES6与ES6是一样的。ES6中的class只是一个语法糖而已。

  • ES5的类中声明类的静态方法
let Animal = function (type) {
  this.type = type
}
Animal.prototype.eat = function () {
  Animal.walk()  //静态方法调用
  console.log("eat eat eat")
}

Animal.walk = function () { //静态方法
  console.log("I can Walk")
}

let dog = new Animal('dog')
dog.eat()
  • ES6的类中声明类的静态方法
class Animal {
  constructor(type) {
    this.type = type
  }
  eat() {
    Animal.walk()  //静态方法调用
    console.log("eat eat eat")
  }
  static walk (){  //静态方法
    console.log("I can walk")
  }
}

let cat = new Animal("cat")
cat.eat()
  • ES5中的继承
    ES5中的继承分为两部:第一步继承父类本身的属性和方法;第二部继承父类原型链上的方法。
let Animal = function (type) {
  this.type = type
}
Animal.prototype.eat = function () {
  console.log("eat eat eat")
}

let Dog = function(){
  // 第一步:初始化父类的构造函数
  Animal.call(this, 'dog')
  this.run = function(){
    console.log('i can run')
  }
}
// 第二步:继承父类的原型
Dog.prototype = Animal.prototype

let dog = new Dog("dog")
dog.eat()  // eat eat eat
  • ES6中的继承
    ES6中的类的继承比ES5简单很多,只需要在定义子类时使用extends关键字即可
class Animal {
  constructor(type) {
    this.type = type
  }
  eat() {
    console.log("eat eat eat")
  }
}

class Dog extends Animal {
  constructor(type) {
    super(type)
  }
}

let dog = new Dog('dog')
dog.eat() //eat eat eat

2.ES6中的set和get

let _age = 1
class Animal{
  constructor(type){
    this.type = type
  }
  eat (){
    console.log("eat eat eat")
  }
  get age(){
    return _age
  }
  set age(val){
    if(val < 5 && val>3){
      _age = val
    }
  }
}

let cat = new Animal("cat")
let dog = new Animal("dog") 

console.log(dog.age) //1
dog.age = 4;
console.log(dog.age) //4
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值