JavaScript面向对象-原型、原型链、继承详解

173 阅读9分钟

一、原型的理解

1.1 对象的原型

  • JavaScript当中任何对象都有一个特殊的内置属性 [[prototype]],即默认的原型(隐式原型)

  • 作用: 在当前对象查找某一个属性时, 如果找不到, 会在原型上面查找

  • 获取原型:

    • 通过对象的 __proto__ 属性可以获取到(但是这个是早期浏览器自己添加的,存在一定的兼容性问题)

    • 通过 Object.getPrototypeOf 方法获取
    var obj = {
      name: "kobe",
      age: 24
    }
    console.log(obj)
    
    // 获取对象的原型
    console.log(obj.name, obj.age) // kobe 24
    console.log(obj.__proto__)
    console.log(Object.getPrototypeOf(obj))
    console.log(obj.__proto__ === Object.getPrototypeOf(obj)) // true
    
    // 这个原型有什么用呢?
    // 当我们通过[[get]]方式获取一个属性对应的value时
    // 1> 它会优先在自己的对象中查找, 如果找到直接返回
    // 2> 如果没有找到, 那么会在原型对象中查找
    console.log(obj.name) // kobe
    
    obj.__proto__.message = "Hello World"
    console.log(obj.message) // Hello World
    

1.2 函数的原型

  • 任何一个函数(非箭头函数),都有自己的prototype属性(函数的显式原型)
    • 不是__proto__
  • 获取原型:
    • prototype
      var obj = {}
      function foo() {}
    
      // 1.将函数看成是一个普通的对象时, 它是具备__proto__(隐式原型)
      // 作用: 查找key对应的value时, 会找到原型身上
      // console.log(obj.__proto__)
      // console.log(foo.__proto__)
    
    
      // 2.将函数看成是一个函数时, 它是具备prototype(显式原型)
      // 作用: 用来构建对象时, 给对象设置隐式原型的
      console.log(foo.prototype)
      // console.log(obj.prototype) 对象是没有prototype
    
  • 作用:
    • 当通过new操作符调用函数时,创建一个新的对象

    • 这个新的对象的隐式原型会指向这个函数的显式原型:obj.__proto__ = F.prototype

      function Foo() {
        // 1.创建空的对象
        // 2.将Foo的prototype原型(显式隐式)赋值给空的对象的__proto__(隐式原型)
      }
      
      console.log(Foo.prototype)
      
      var f1 = new Foo()
      var f2 = new Foo()
      var f3 = new Foo()
      console.log(f1.__proto__)
      console.log(f1.__proto__ === Foo.prototype) // true
      console.log(f3.__proto__ === f5.__proto__) // true
      

1.3 构造函数正确的写法

function Student(name, age, sno) {
  this.name = name
  this.age = age
  this.sno = sno

  // 1.方式一: 编写函数, 会创建很多个函数对象
  // this.running = function() {
  //   console.log(this.name + " running")
  // }
  // this.eating = function() {
  //   console.log(this.name + " eating")
  // }
  // this.studying = function() {
  //   console.log(this.name + " studying")
  // }
}

// 当多个对象拥有共同的值时, 可以将它放到构造函数对象的显式原型
// 由构造函数创建出来的所有对象, 都会共享这些属性
Student.prototype.running = function() {
  console.log(this.name + " running")
}
Student.prototype.eating = function() {
  console.log(this.name + " eating")
}

// 1.创建三个学生
var stu1 = new Student("lilei", 18, 111)
var stu2 = new Student("hanmeimei", 17, 112)
var stu3 = new Student("jim", 18, 113)

// 隐式原型的作用
// 1> stu1的隐式原型是Student.prototype对象
// 2> stu1.running查找:
//  * 先在自己身上查找, 没有找到
//  * 去原型去查找
stu1.running()
stu2.eating()

1.4 显式原型上的constructor

  • 事实上原型对象上面是有一个属性的:constructor

    • 默认情况下原型上都会添加一个属性叫做constructor,这个constructor指向当前的函数对象
    // 非常重要的属性: constructor, 指向Person函数对象
    function Person() {
    
    }
    
    // 1.对constructor在prototype上的验证
    var PersonPrototype = Person.prototype
    console.log(PersonPrototype)
    console.log(PersonPrototype.constructor)
    console.log(PersonPrototype.constructor === Person) // true
    
    console.log(Person.name) // Person
    console.log(PersonPrototype.constructor.name) // Person
    
    // 2.实例对象p
    var p = new Person()
    console.log(p.__proto__.constructor)
    console.log(p.__proto__.constructor.name) // Person
    

1.5 创建对象过程的内存图

function Person(name, age) {
  this.name = name
  this.age = age
}

Person.prototype.running = function() {
  console.log("running~")
}

var p1 = new Person("why", 18)
var p2 = new Person("kobe", 30)

// 进行操作
console.log(p1.name) // why
console.log(p2.name) // kobe

p1.running()
p2.running()

// 新增属性
Person.prototype.address = "中国"
p1.__proto__.info = "中国很美丽!"

p1.height = 1.88
p2.isAdmin = true

// 修改address
p1.address = "广州市"
console.log(p2.address) // 中国
  • 内存图 image.png

1.6 重写显式原型

  • 如果需要在原型上添加过多的属性,通常会重写整个原型对象:

  • 前面说过, 每创建一个函数, 就会同时创建它的prototype对象, 这个对象也会自动获取constructor属性;

    • 而我们这里相当于给prototype重新赋值了一个对象, 那么这个新对象的constructor属性,会指向Object构造函数, 而不是Person构造函数
  • 默认情况下, 原生的constructor属性是不可枚举的

    function Person() {
    
    }
    
    console.log(Person.prototype)
    
    // 在原有的原型对象上添加新的属性
    // Person.prototype.message = "Hello Person"
    // Person.prototype.info = { name: "哈哈哈", age: 30 }
    // Person.prototype.running = function() {}
    // Person.prototype.eating = function() {}
    
    // console.log(Person.prototype)
    // console.log(Object.keys(Person.prototype))
    
    // 直接赋值一个新的原型对象
    Person.prototype = {
      message: "Hello Person",
      info: { name: "哈哈哈", age: 30 },
      running: function() {},
      eating: function() {},
      // constructor: Person
    }
    
    // 修改constructor,跟默认一致
    Object.defineProperty(Person.prototype, "constructor", {
      enumerable: false,
      configurable: true,
      writable: true,
      value: Person
    })
    
    console.log(Object.keys(Person.prototype))
    
    // 新建实例对象
    var p1 = new Person() // ['message', 'info', 'running', 'eating']
    console.log(p1.message) // Hello Person
    

二、ES5中的继承

2.1 面向对象的三大特性

  • 封装:将属性和方法封装到一个类中,可以称之为封装的过程

  • 继承:继承是面向对象中非常重要的,不仅仅可以减少重复代码的数量,也是多态前提(纯面向对象中)

    • 继承可以将重复的代码和逻辑抽取到父类中,子类只需要直接继承过来使用即可
  • 多态:不同的对象在执行时表现出不同的形态

2.2 原型链的概念

  • 每个对象都有自己的原型对象,原型对象也有自己的原型对象。在访问对象的属性时,会沿着对象自身=>自身的原型对象=>原型对象的原型对象......这样的链条一路查找上去,这条链式结构就叫做原型链。原型链的尽头是Object的原型对象的[[prototype]]属性,值为null

    // 1.{}的本质
    // var info = {}
    // 相当于
    // var info = new Object()
    // console.log(info.__proto__ === Object.prototype)
    
    // 2.原型链
    var obj = {
      name: "kobe",
      age: 24
    }
    
    // 查找顺序
    // 1.obj上面查找
    // 2.obj.__proto__上面查找
    // 3.obj.__proto__.__proto__ -> null 上面查找(undefined)
    // console.log(obj.message)
    
    
    // 3.对现有代码进行改造
    obj.__proto__ = {
      // message: "Hello aaa"
    }
    
    obj.__proto__.__proto__ = {
      // message: "Hello bbbb"
    }
    
    obj.__proto__.__proto__.__proto__ = {
      message: "Hello ccc"
    }
    
    console.log(obj.message) // Hello ccc
    
  • 什么地方是原型链的尽头呢?

    • Object是所有类的父类,原型链最顶层的原型对象就是Object的原型对象

    • Object直接创建出来的对象的原型都是 [Object: null prototype] {}

      • 该对象有原型属性,但是它的原型属性已经指向的是null,也就是已经是顶层原型
      • 该对象上有很多默认的属性和方法
  • 创建Object对象的内存图

    image.png

2.3 原型实现继承

原型链继承:重写子类的显式原型对象,让子类的显式原型对象的隐式原型指向父类的显式原型对象

  • 定义一个Person类,让子类Student继承Person类
function Person(name, age) {
  this.name = name
  this.age = age
}

Person.prototype.running = function() {
  console.log("running~")
}
Person.prototype.eating = function() {
  console.log("eating~")
}

function Student(name, age, sno, score) {
  this.name = name
  this.age = age

  this.sno = sno
  this.score = score
}
  • 父类的原型直接赋值给子类的原型(错误的做法)

    • 缺点: 父类和子类共享通一个原型对象, 修改了任意一个, 另外一个也被修改
    Student.prototype = Person.prototype
    
    Student.prototype.studying = function() {
      console.log("studying~")
    }
    
    var stu1 = new Student("lileilei", 18 "111", 99)
    
  • 创建一个父类的实例对象(new Person()), 用这个实例对象来作为子类的原型对象

    • 缺点:给子类型原型添加属性和方法必须在替换原型之后; 重写父类的参数(name, age); 子类型的原型上的 constructor 属性被重写,需要手动修改
    var p = new Person()
    Student.prototype = p
    // 重写 Student.prototype 的 constructor 属性,指向自己的构造函数 Student
    Student.prototype.constructor = Student
    
    Student.prototype.studying = function() { // 必须在上面代码下面写
      console.log("studying~")
    }
    
    var stu2 = new Student("hanmeimei", 17, "112", 98)
    
  • 内存图
    image.png

2.4 借用构造函数继承

  • 借用继承的做法非常简单:在子类型构造函数的内部调用父类型构造函数

    • 函数可以在任意的时刻被调用

    • 通过apply()和call()方法也可以在新创建的对象上执行构造函数

    var p = new Person()
    Student.prototype = p
    // 重写 Student.prototype 的 constructor 属性,指向自己的构造函数 Student
    Student.prototype.constructor = Student
    
    function Student(name, age, sno, score) {
      // 重点: 借用构造函数
      Person.call(this, name, age)
      // this.name = name
      // this.age = age
    
      this.sno = sno
      this.score = score
    }
    
  • 组合继承存在的问题

    • 组合继承最大的问题就是无论在什么情况下,都会调用两次父类构造函数

      • 一次在创建子类原型的时候 var p = new Person()

      • 另一次在子类构造函数内部(也就是每次创建子类实例的时候) Person.call(this, name, age)

    • 所有的子类实例事实上会拥有两份父类的属性

      • 一份在当前的实例自己里面(也就是p本身的),另一份在子类对应的原型对象中(也就是p.__proto__里面)

      • 当然,这两份属性我们无需担心访问出现问题,因为默认一定是访问实例本身这一部分的

      image.png

2.5 原型式/寄生式思想

  • 原型式继承的渊源

    • 这种模式要从道格拉斯·克罗克福德(Douglas Crockford,著名的前端大师,JSON的创立者)在2006年写的一篇文章说起: Prototypal Inheritance in JavaScript(在JavaScript中使用原型式继承)

      • 在这篇文章中,它介绍了一种继承方法,而且这种继承方法不是通过构造函数来实现的
  • 原型链继承的实现过程:

    • 必须创建一个对象
    • 这个对象的隐式原型指向父类的显式原型
    • 将这个对象赋值给子类的显示原型
  • 创建这个原型对象的方法

    // 工具函数
    // 创建对象的过程
    function createObject(o) {
      function F() {}
      F.prototype = o
      return new F()
    }
    
    // 将Subtype和Supertype联系在一起
    // 寄生式函数
    function inherit(Subtype, Supertype) {
      // Subtype.prototype = Object.create(Supertype.prototype)
      // Object.setPrototypeOf(Subtype.prototype, Supertype.prototype)
      Subtype.prototype = createObject(Supertype.prototype)
      Object.defineProperty(Subtype.prototype, "constructor", {
        enumerable: false,
        configurable: true,
        writable: true,
        value: Subtype
      })
    }
    
    function Person(name, age, height) {}
    function Student() {}
    
    inherit(Student, Person)
    
    // 1.之前的做法: 但是不想要这种做法
    // var p = new Person()
    // Student.prototype = p
    
    // 2.方案一:
    var obj = {}
    // obj.__proto__ = Person.prototype
    Object.setPrototypeOf(obj, Person.prototype)
    Student.prototype = obj
    
    // 3.方案二:
    // function F() {}
    // F.prototype = Person.prototype
    // Student.prototype = new F()
    
    // 4.方案三:
    var obj = Object.create(Person.prototype)
    console.log(obj.__proto__ === Person.prototype) // true
    Student.prototype = obj
    

2.6 寄生组合式继承

function Person(name, age, height) {
  this.name = name
  this.age = age
  this.height = height
}

Person.prototype.running = function() {
  console.log("running~")
}
Person.prototype.eating = function() {
  console.log("eating~")
}


function Student(name, age, height, sno, score) {
  Person.call(this, name, age, height)
  this.sno = sno
  this.score = score
}

inherit(Student, Person)
Student.prototype.studying = function() {
  console.log("studying")
}

// 创建实例对象
var stu1 = new Student("kobe", 26, 1.88, 111, 100)

2.7 Object是最终的父类

  • 所有的类都继承自Object
function Person() {}
function Student() {}
function Teacher() {}

inherit(Student, Person)
console.log(Person.prototype.__proto__ === Object.prototype)

// 在Object的原型上添加属性
Object.prototype.message = "哈哈哈"
var stu = new Student()
console.log(stu.message)

// Object原型上本来就已经存放一些方法
console.log(Object.prototype)
console.log(stu.toString())

// 函数对象也是最终继承自Object
function foo() {}
console.log(foo.message)
  • 内存图 image.png

2.8 对象判断方法补充

  • hasOwnProperty

    • 对象是否有某一个属于自己的属性(不是在原型上的属性)
  • in/for in 操作符

    • 判断某个属性是否在某个对象或者对象的原型上
  • instanceof

    • 用于检测构造函数(Person、Student类)的pototype,是否出现在某个实例对象的原型链上
  • isPrototypeOf

    • 用于检测某个对象,是否出现在某个实例对象的原型链上
    function createObject(o) {
      function F() {}
      F.prototype = o
      return new F()
    }
    
    var obj = {
      name: "kobe",
      age: 24
    }
    
    var info = createObject(obj)
    info.address = "中国"
    info.intro = "中国大好河山"
    
    console.log(info.name, info.address)
    console.log(info)
    
    // 1.hasOwnProperty
    // console.log(info.hasOwnProperty("name")) // false
    // console.log(info.hasOwnProperty("address")) // true
    
    // 2.in操作符
    console.log("name" in info)
    console.log("address" in info)
    // 注意: for in遍历不仅仅是自己对象上的内容, 也包括原型对象上的内容
    for (var key in info) {
      console.log(key)
    }
    
    // 3.instanceof
    // instanceof用于判断对象和类(构造函数)之间的关系
    function Person() {}
    function Student() {}
    inherit(Student, Person)
    
    // stu实例(instance)对象
    var stu = new Student()
    console.log(stu instanceof Student) // true
    console.log(stu instanceof Person) // true
    console.log(stu instanceof Object) // true
    console.log(stu instanceof Array) // false
    
    // 4.isPrototypeOf
    console.log(Student.prototype.isPrototypeOf(stu)) // true
    console.log(Person.prototype.isPrototypeOf(stu)) // true
    
    // 可以用于判断对象之间的继承
    console.log(obj.isPrototypeOf(info)) // true
    

三、原型关系图

var obj = {} // new Object()
obj.__proto__ // Object.prototype

function foo() {} // new Function()
console.log(foo.length, foo.name) // 0 'foo'
console.log(foo.__proto__) // Function.prototype

function Person() { // Person.__proto === Function.prototype

}

console.log(foo.__proto__ === Function.prototype) // true
console.log(Person.__proto__ === Function.prototype) // true
console.log(foo.__proto__ === Person.__proto__) // true
console.log(Object.__proto__ === Function.prototype) // true
console.log(Function.__proto__ === Function.prototype) // true

var p1 = new Person()
var p2 = new Person()

console.log(Object.prototype)
  • 结论

    1. p1是Person的实例对象
    2. obj是Object的实例对象
    3. Function/Object/Foo都是Function的实例对象
    4. 原型对象默认创建时, 隐式原型都是指向Object的显式原型的(Object指向null)
      • 推导另外一个结论:Object是Person/Function的父类

    image.png

  • 原型继承关系 image.png