JavaScript 面向对象编程

目录

  • 封装
  • 继承
  • 多态

和其他语言的面向对象不同,JS 的面向对象是基于原型的。

封装

封装就是信息隐藏,有两层含义,一个是隐藏方法的具体实现细节,另一个是属性/方法的可见性(JS 没有访问权限修饰符)

function Animal(name, age) {
  this.name = name;
  this.age = age;
}

Animal.prototype.talk = function () {
  console.log(`I'm ${this.name}, I'm ${this.age} 了`);
}

const animal = new Animal('小动物', 18);
animal.talk(); // talk 的具体实现我们并不知道,这是封装

JS 没有访问权限修饰符,只能变通实现,比如约定下划线开头的是私有属性

function Animal(name, age) {
  this.name = name;
  this._age = age;
}

也可以用 Symbol

const ageSym = Symbol('年龄');

function Animal(name, age) {
  this.name = name;
  this.ageSym = age;
}

继承

继承是扩展父类的一种方式,不同的是 JS 的继承是对象与对象之间。

function Dog(name, age) {
  // 继承实例属性
  Animal.call(this, name, age);
}

// 继承原型上的属性/方法
Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.constructor = Dog;

// 这里可以写成方法
// function inherit(Parent, Child) {
//   Child.prototype = Object.create(Parent.prototype);
//   Child.prototype.constructor = Child;
// }
// inherit(Animal, Dog);

const dog = new Dog('小狗狗', 18);
dog.talk();

多态

同一父类的不同子类的实例,调用相同的方法可以有不同的表现,这就叫多态。可以在子类中通过方法覆写、重载实现,JS 没有重载

function Dog(name, age) {
  Animal.call(this, name, age);
}

inherit(Animal, Dog);

Dog.prototype.talk = function () {
  console.log(`I'm ${this.name}, I'm ${this.age} 了,旺旺`);
}

function Cat(name, age) {
  Animal.call(this, name, age);
}

inherit(Animal, Cat);

Cat.prototype.talk = function () {
  console.log(`I'm ${this.name}, I'm ${this.age} 了,喵喵`);
}

const dog = new Dog('小狗狗', 18);
dog.talk(); // I'm 小狗狗, I'm 18 了,旺旺

const cat = new Cat('小猫咪', 6);
cat.talk(); // I'm 小猫咪, I'm 6 了,喵喵

你可能感兴趣的:(前端基础)