ES6对象模块(一) --- ES6的面向对象

一、面向对象

1.1 ES5的面向对象

  • ES5 实际上不是真的面向对象
  • 没有统一的写法
// 1. 既是构造函数,又是类
function Person (name, age) {  
  this.name = name;
  this.age = age;
}

// 2. 方法在类之外
Person.prototype.show = function() {}

// 3. 没有专门的继承
function worker(name, age, job) {
  // 4. 从父类继承的一种方式
  Person.call(this, name, age)
  this.job = job
}

// 5. 没有专门继承父类的方法
worker.prototype = new Person()
worker.prototype.constructor = worker;

1.2、ES6的面向对象

提供4个新的关键词,用于解决上面的问题

  • class :类声明
  • constructor :构造函数/构造器
  • extends :继承
  • super :超类/父类

ES6对于面向对象的好处

  • 有一个统一的写法
// 有了单独类的声明
class Person {
  // 也有了单独的 构造函数 的声明
  constructor(name, age) {
    this.name = name;
    this.age = age
  }
  // 方法也可以直接写在里面
  getName() {
    return this.name
  }
  setName(name) {
    this.name = name
  }
}
let person = new Person("duck", 18)
console.log(person.getName())
  • 有一个正规的继承方式
class Worker extends Person{
  constructor(name, age, job) {
     super(name, age);
     this.job = job
   }
   getJob() {
     return this.job
   }
}
let woker = new Worker("pig", 6, "pigpig")
console.log(woker.getJob())
console.log(woker.getName())
原创文章 35 获赞 14 访问量 2368

猜你喜欢

转载自blog.csdn.net/pig_is_duck/article/details/106009786