面向对象

类的声明

使用构造函数声明

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

使用 class 声明类

class Animal {
    constructor(name) {
        this.name = name;
    }
}

类的实例化

使用 new 操作符来实例化一个类

const animal = new Animal('dog');

类的继承

借助构造函数实现继承

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

Animal.prototype.say = function() {
    console.log("I'm Animal");
};

function Dog() {
    Animal.call(this);
    this.eyes = 2;
}
console.log(new Dog().say()); // 报错

缺点:通过这种方式实现的继承是部分继承,只能继承构造函数中的内容,不能继承父类原型链上的属性。

借助原型链实现继承

function Animal(name){
    this.name = name;
    this.numbers = [1, 2, 3];
}

Animal.prototype.say = function() {
    console.log("I'm Animal");
};

function Dog() {
    this.eyes = 2;
}

Dog.prototype = new Animal();

缺点:如果通过 Dog 实例化两个对象,当其中一个对象对原型中的数据发生修改时,因为两个实例拥有同一个原型,所以第二个实例也会发生对应的变化。

const dog1 = new Dog();
const dog2 = new Dog();
dog1.numbers.push(4); // [1, 2, 3, 4]
console.log(dog2.numbers); // [1, 2, 3, 4]

组合方式

function Animal(name){
    this.name = name;
    this.numbers = [1, 2, 3];
}

Animal.prototype.say = function() {
    console.log("I'm Animal");
};

function Dog() {
    Animal.call(this);
    this.eyes = 2;
}

Dog.prototype = new Animal();

const dog1 = new Dog();
const dog2 = new Dog();
dog1.numbers.push(4); // [1, 2, 3, 4]
console.log(dog2.numbers); // [1, 2, 3]

缺点:父类声明了两次

组合方式优化

function Animal(name){
    this.name = name;
    this.numbers = [1, 2, 3];
}

Animal.prototype.say = function() {
    console.log("I'm Animal");
};

function Dog() {
    Animal.call(this);
    this.eyes = 2;
}

Dog.prototype = Animal.prototype;

const dog1 = new Dog();
const dog2 = new Dog();
dog1.numbers.push(4); // [1, 2, 3, 4]
console.log(dog2.numbers); // [1, 2, 3]

缺点:实例对象的 constructor 指向父类而不是指向构造函数

组合方式2

function Animal(name){
    this.name = name;
    this.numbers = [1, 2, 3];
}

Animal.prototype.say = function() {
    console.log("I'm Animal");
};

function Dog() {
    Animal.call(this);
    this.eyes = 2;
}

Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.constructor = Dog;

const dog1 = new Dog();
const dog2 = new Dog();
dog1.numbers.push(4); // [1, 2, 3, 4]
console.log(dog2.numbers); // [1, 2, 3]
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  •   面向对象(Object-Oriented,OO)的语言有一个标志,那就是它们都有类的概念,而通过类可以创建任意...
    霜天晓阅读 2,228评论 0 6
  • 博客内容:什么是面向对象为什么要面向对象面向对象编程的特性和原则理解对象属性创建对象继承 什么是面向对象 面向对象...
    _Dot912阅读 1,519评论 3 12
  • JavaScript面向对象程序设计 本文会碰到的知识点:原型、原型链、函数对象、普通对象、继承 读完本文,可以学...
    moyi_gg阅读 819评论 0 2
  • 面向对象编程是用抽象方式创建基于现实世界模型的一种编程模式,主要包括模块化、多态、和封装几种技术。对 JavaSc...
    吴佳浩阅读 589评论 0 4
  • 傅园慧又开直播,IP到底有多大号召力 新晋网红傅园慧自里约奥运会后热度持续上升,她个性十足的夸张表情和不按套路出牌...
    衬人新欢i阅读 410评论 0 0

友情链接更多精彩内容