实现面向对象编程OOP(简易模型)

面向对象编程 OOP

面向对象的三大特征: 封装、继承、多态。
  • 封装:把某些相同的属性或者方法都写入一个函数里面。

  • 继承:纵向的关系。

  • 多态:横向并列的类型。

  • 示例

// 封装
function Person(name, age) {
  this.name = name;
  this.age = age;
  this.say = function() {
  // 大家都有的方法
    return console.log(`这个人说HAha。`);
  }
}

// 原型继承 每一个函数都有一个显式原型(prototype) 并且prototype.constructor构造函数又是该函数本身
console.log(Person.prototype.constructor === Person); // true
Person.prototype.eat = function() {
  return console.log(`${this.name}在吃烤鱼。`)
}


// 体现多态的写法 say方法
function China(name, age) {
  // 使用call 或者 apply 继承属性
  Person.call(this, name, age);
  this.say = function() {
    return console.log(`${this.name}说中文。`)
  }
}
function American(name, age) {
  // 使用call 或者 apply 继承属性
  Person.call(this, name, age);
  this.say = function(){
    return console.log(`${this.name}说English。`)
  }
}

// 使用原型继承方法
China.prototype = new Person();
American.prototype = new Person();

const C1 = new China('小赵', 19);
const A1 = new American('Jerry', 30);

console.log(C1, A1);

console.log(China.prototype.say());
  • 总结:
    • 继承属性是有call/apply继承,继承方法使用原型继承。
    • 再来一句软件编程的总的原则:低耦合,高内聚
posted @ 2022-04-21 18:09  lutwelve  阅读(33)  评论(0编辑  收藏  举报