饥人谷技术博客收藏

ES6(8)、新版的类

2022-04-14  本文已影响0人  飞天小猪_pig
1、什么是类

类是拥有相同属性的对象,用于创建对象的模板。

2、如何实现类
1、ES6之前:

(1)、实现简单的类:例1

function Dog(name){   //定义Dog是一种类,名字大写
  this.name = name   //可以在对象内定义自有属性
  this.legsNumber = 4
}
Dog.prototype.kind = '狗'   //可以定义公有属性是kind
Dog.prototype.say = function(){  //可以定义公有属性say方法
  console.log(`我是${this.name},我有${this.legsNumber}条腿。`)
}

const d1 = new Dog('旺财') // Dog 函数就是一个类
d1.say()  //打印出:我是旺财,我有4条腿。

(2)、实现类的继承:例2

function Animal(legsNumber){   //父类Animal
  this.legsNumber = legsNumber  //父类的自有属性
}
Animal.prototype.kind = '动物'   //父类的公有属性

function Dog(name){   //子类继承父类方法和自有属性
  this.name = name
  Animal.call(this, 4) // 关键代码1
  }
Dog.prototype.__proto__ = Animal.prototype // 关键代码2,但这句代码被禁用了,怎么办

Dog.prototype.kind = '狗'
Dog.prototype.say = function(){
  console.log(`我是${this.name},我有${this.legsNumber}条腿。`)
}

const d1 = new Dog('旺财') // Dog 函数就是一个类
console.dir(d1)

上述子类实现父类继承是关键代码1和关键代码2两处

Dog.prototype.__proto__ = Animal.prototype // 一般不推荐这样写

如果这句代码不被推荐或者被禁用了,可以写成下面的:

var f = function(){ }
f.prototype = Animal.prototype
Dog.prototype = new f()
2、ES6:更加规范化去定义一个类。

语法:

class xxx {   //首先先写class代表这是一个类对象,xxx是表示一个类的名字(大写)
  constructor(a) {  //constructor构造函数,可以进行传参,里面主要是定义类的自有属性
     ...
  }
  yyy(){   //yyy表示xxx类的公有属性的方法
    ...
  }
}
const d1 = new xxx('')  //

(1)、将上述例1改成ES6用class生成的类:

class Dog {
  kind = '狗' // 等价于在 constructor 里写 this.kind = '狗'
  constructor(name) {
    this.name = name
    this.legsNumber = 4
  }
  say(){
    console.log(`汪汪汪~ 我是${this.name},我有${this.legsNumber}条腿。`)
  }
}
const d1 = new Dog('旺财')
d1.say() 

(2)、将上述例2改成ES6用class生成的类:

class Animal{
  constructor(legsNumber){
    this.legsNumber = legsNumber
  }
}

class Dog extends Animal{   //在子类中使用extends关键字,代表Dog继承Animal
  constructor(name) {
    super(4)   //使用关键字super()代表使用父类方法和属性
    this.name = name
  }
  say(){
    console.log(`汪汪汪~ 我是${this.name},我有${this.legsNumber}条腿。`)
  }
}

const d1 = new Dog('旺财') // Dog 函数就是一个类
console.dir(d1)
上一篇 下一篇

猜你喜欢

热点阅读