Skip to content

认识对象的原型

JavaScript当中每个对象都有一个特殊的内置属性 [[prototype]],这个特殊的对象可以指向另外一个对象。

那么这个对象有什么用呢?

当我们通过引用对象的属性key来获取一个value时,它会触发 [[Get]]的操作;

这个操作会首先检查该对象是否有对应的属性,如果有的话就使用它;

如果对象中没有改属性,那么会访问对象[[prototype]]内置属性指向的对象上的属性;

那么如果通过字面量直接创建一个对象,这个对象也会有这样的属性吗?如果有,应该如何获取这个属性呢?

答案是有的,只要是对象都会有这样的一个内置属性;

获取的方式有两种:

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

方式二:通过 Object.getPrototypeOf 方法可以获取到;

javascript
var obj = {
    name: "why",
    age: 18
}
console.log(obj)

var info = {}

// 获取对象的原型
console.log(obj.name, obj.age)
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)

obj.__proto__.message = "Hello World"
console.log(obj.message)

函数的原型 prototype

那么我们知道上面的东西对于我们的构造函数创建对象来说有什么用呢?

它的意义是非常重大的,接下来我们继续来探讨;

这里我们又要引入一个新的概念:所有的函数都有一个prototype的属性(注意:不是__proto__

你可能会问,是不是因为函数是一个对象,所以它有prototype的属性呢?

不是的,因为它是一个函数,才有了这个特殊的属性;

而不是它是一个对象,所以有这个特殊的属性;

javascript
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操作符原型赋值

我们前面讲过new关键字的步骤如下:

1.在内存中创建一个新的对象(空对象);

2.这个对象内部的[[prototype]]属性会被赋值为该构造函数的prototype属性;

那么也就意味着我们通过Person构造函数创建出来的所有对象的[[prototype]]属性都指向Person.prototype:

javascript
function Foo() {
    // 1.创建空的对象
    // 2.将Foo的prototype原型(显式隐式)赋值给空的对象的__proto__(隐式原型)
}

console.log(Foo.prototype)

var f1 = new Foo()
var f2 = new Foo()
var f3 = new Foo()
var f4 = new Foo()
var f5 = new Foo()
console.log(f1.__proto__)
console.log(f1.__proto__ === Foo.prototype) // true
console.log(f3.__proto__ === f5.__proto__) // true

将方法放在原型上

创建一个Student构造函数,通过这个构造函数来创建三个学生,每个学生都有自己的name,age,sno;除此之外,我们还可以定义学生的一些方法,比如running,eating,studying。这样是可以创建三个学生对象,但是同时也意味着每创建一个学生对象,就会创建一个函数对象,如果有一百个学生就会创建一百个,会占据内存。那么,我们就可以将这些公共的方法放在构造函数的原型上。

javascript
/*
    1.什么是函数的显式原型
      * 区分和对象原型区别
    2.函数的原型的作用
      * 在通过new操作创建对象时, 将这个显式原型赋值给创建出来对象的隐式原型
    3.案例Person, 将所有的函数定义放到了显式原型上
*/

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("why", 18, 111)
var stu2 = new Student("kobe", 30, 112)
var stu3 = new Student("james", 32, 113)

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

constructor属性

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

默认情况下原型上都会添加一个属性叫做constructor,这个constructor指向当前的函数对象;

javascript
// 非常重要的属性: constructor, 指向Person函数对象
function Person() {

}

// 1.对constructor在prototype上的验证
var PersonPrototype = Person.prototype
console.log(PersonPrototype)
console.log(PersonPrototype.constructor) // Person函数对象
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) // Person函数对象
console.log(p.__proto__.constructor.name) // Person

创建对象过程内存

javascript
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

// 获取属性
console.log(p1.address) // 中国
console.log(p2.isAdmin) // true
console.log(p1.isAdmin) // undefined
console.log(p2.info) // 中国很美丽

// 修改address
p1.address = "广州市"
console.log(p2.address) // 中国

image-20230105200238523

重写原型对象

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

javascript
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 这么写的话,默认是可枚举的,Object.keys可以拿到constructor属性
}

// 默认情况下, 原生的constructor属性是不可枚举的
Object.defineProperty(Person.prototype, "constructor", {
    enumerable: false,
    configurable: true,
    writable: true,
    value: Person
})

console.log(Object.keys(Person.prototype))

// 新建实例对象
var p1 = new Person()
console.log(p1.message)

面向对象的特性 – 继承

面向对象有三大特性:封装、继承、多态

封装:我们前面将属性和方法封装到一个类中,可以称之为封装的过程;

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

多态:不同的对象在执行时表现出不同的形态;

那么这里我们核心讲继承。

那么继承是做什么呢?

继承可以帮助我们将重复的代码和逻辑抽取到父类中,子类只需要直接继承过来使用即可;

在很多编程语言中,继承也是多态的前提;

那么JavaScript当中如何实现继承呢?

不着急,我们先来看一下JavaScript原型链的机制;

再利用原型链的机制实现一下继承;

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

Student.prototype.running = function() {}
Student.prototype.eating = function() {}
Student.prototype.studying = function() {}


function Teacher(name, age, title) {
    this.name = name
    this.age = age
    this.title = tilte
}

Teacher.prototype.running = function() {}
Teacher.prototype.eating = function() {}
Teacher.prototype.teach = function() {}

JavaScript原型链

在真正实现继承之前,我们先来理解一个非常重要的概念:原型链。

我们知道,从一个对象上获取属性,如果在当前对象中没有获取到就会去它的原型上面获取:

javascript
// 1.{}的本质
// var info = {}
// 相当于
// var info = new Object()
// console.log(info.__proto__ === Object.prototype)

// 2.原型链
var obj = {
    name: "why",
    age: 18
}

// 查找顺序
// 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)

Object的原型

那么什么地方是原型链的尽头呢?比如第三个对象是否也是有原型__proto__属性呢?

javascript
console.log(obj.__proto__.__proto__.__proto__.__proto__) //  [Object: null prototype] {}

我们会发现它打印的是 [Object: null prototype] {}

事实上这个原型就是我们最顶层的原型了

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

那么我们可能会问: [Object: null prototype] {} 原型有什么特殊吗?

特殊一:该对象有原型属性,但是它的原型属性已经指向的是null,也就是已经是顶层原型了;

特殊二:该对象上有很多默认的属性和方法;

创建Object对象的内存图

image-20230105224855517

通过原型链实现方法继承

如果我们现在需要实现继承,那么就可以利用原型链来实现了:

javascript
// 定义Person构造函数(类)
function Person(name, age, height, address) {
    this.name = name
    this.age = age
    this.height = height
    this.address = address
}

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.running = function() {
//   console.log("running~")
// }
// Student.prototype.eating = function() {
//   console.log("eating~")
// }
Student.prototype.studying = function() {
    console.log("studying~")
}
// 创建学生
var stu1 = new Student("kobe", 30, 111, 100)
stu1.running()

image-20230105210023075

如果将父类的原型直接赋值给子类的原型,那么Person的显式原型会多出来一个studying方法。

javascript
var p = new Person()
p.studying() // 原本Person的原型对象上没有studying方法,现在却可以访问了
javascript
// 方式二: 创建一个父类的实例对象(new Person()), 用这个实例对象来作为子类的原型对象
var p = new Person("why", 18)
Student.prototype = p

var stu1 = new Student("kobe", 30, 111, 100)
stu1.running() // 可以访问,最终会找到Person显式原型对象上的running方法

var p2 = new Person()
p2.studying() // 这个时候就访问不到studying方法,因为Person的显式原型对象没有这个方法

image-20230105211453265

原型链继承的弊端

但是目前有一个很大的弊端:某些属性其实是保存在p对象上的;

第一,我们通过直接打印对象是看不到这个属性的;

我们将下面两行代码注释,因为父类Person已经有了相同的代码。在这种情况下打印p

javascript
var p = new Person("why", 18)
Student.prototype = p

// 定义学生类
function Student(name, age,  sno, score) {
    // this.name = name
    // this.age = age
    this.sno = sno
    this.score = score
}

var stu1 = new Student("kobe", 30, 111, 100)
console.log(stu1) // 看不到name和age属性,它们是保存在p对象上

第二,这个属性会被多个对象共享,如果这个对象是一个引用类型,那么就会造成问题;

可以看到创建多个对象,共享的都是p对象,它们打印出来的值相同,本来是不同的,都有自己的name和age。

第三,不能给Person传递参数(让每个stu有自己的属性),因为这个对象是一次性创建的(没办法定制化);

不能将自己的name和age传递给Person,一开始就写死了,why和18

javascript
var p = new Person("why", 18)
Student.prototype = p

var stu1 = new Student("kobe", 30, 111, 100)
var stu2 = new Student("james", 25, 111, 100)

console.log(stu1.name, stu1.age) // why 18
console.log(stu2.name, stu2.age) // why 18

借用构造函数实现属性继承

为了解决原型链继承中存在的问题,开发人员提供了一种新的技术: constructor stealing(有很多名称: 借用构造函数或者称之 为经典继承或者称之为伪造对象):

steal是偷窃、剽窃的意思,但是这里可以翻译成借用;

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

因为函数可以在任意的时刻被调用;

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

javascript
// 定义Person构造函数(类)
function Person(name, age, height, address) {
    this.name = name
    this.age = age
    this.height = height
    this.address = address
}

// 定义学生类
function Student(name, age, height, address, sno, score) {
    // 重点: 借用构造函数
    Person.call(this, name, age, height, address)
    // this.name = name
    // this.age = age
    // this.height = height
    // this.address = address

    this.sno = sno
    this.score = score
}

组合借用继承的问题

组合继承是JavaScript最常用的继承模式之一:

如果你理解到这里, 点到为止, 那么组合来实现继承只能说问题不大;

但是它依然不是很完美,但是基本已经没有问题了;

javascript
// 定义Person构造函数(类)
function Person(name, age, height, address) {
    this.name = name
    this.age = age
    this.height = height
    this.address = address
}

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

// 定义学生类
function Student(name, age, height, address, sno, score) {
    // 重点: 借用构造函数
    Person.call(this, name, age, height, address)
    // this.name = name
    // this.age = age
    // this.height = height
    // this.address = address

    this.sno = sno
    this.score = score
}

// 方式一: 父类的原型直接赋值给子类的原型
// 缺点: 父类和子类共享通一个原型对象, 修改了任意一个, 另外一个也被修改
// Student.prototype = Person.prototype

// 方式二: 创建一个父类的实例对象(new Person()), 用这个实例对象来作为子类的原型对象
var p = new Person("why", 18)
Student.prototype = p

// Student.prototype.running = function() {
//   console.log("running~")
// }
// Student.prototype.eating = function() {
//   console.log("eating~")
// }
Student.prototype.studying = function() {
    console.log("studying~")
}

// 创建学生
var stu1 = new Student("kobe", 30, 111, 100)
var stu2 = new Student("james", 25, 111, 100)
stu1.running()
stu1.studying()

console.log(stu1.name, stu1.age)
console.log(stu1)
console.log(stu2.name, stu2.age)

组合继承存在什么问题呢?

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

一次在创建子类原型的时候;

javascript
// 方式二: 创建一个父类的实例对象(new Person()), 用这个实例对象来作为子类的原型对象
var p = new Person("why", 18)
Student.prototype = p

另一次在子类构造函数内部(也就是每次创建子类实例的时候);

javascript
// 定义学生类
function Student(name, age, height, address, sno, score) {
    // 重点: 借用构造函数
    Person.call(this, name, age, height, address)
    // this.name = name
    // this.age = age
    // this.height = height
    // this.address = address

    this.sno = sno
    this.score = score
}

另外,如果你仔细按照我的流程走了上面的每一个步骤,你会发现:所有的子类实例事实上会拥有两份父类的属性

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

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

image-20230105220056870

寄生组合式继承

现在我们来回顾一下之前提出的比较理想的组合继承

组合继承是比较理想的继承方式, 但是存在两个问题:

问题一:构造函数会被调用两次: 一次在创建子类型原型对象的时候, 一次在创建子类型实例的时候。

问题二: 父类型中的属性会有两份: 一份在原型对象中, 一份在子类型实例中。

事实上, 我们现在可以利用寄生式继承将这两个问题给解决掉。

你需要先明确一点:当我们在子类型的构造函数中调用父类型.call(this, 参数)这个函数的时候, 就会将父类型中的属性和方法复制一份到了子类型中.。所以父类型本身里面的内容, 我们不再需要。

这个时候, 我们还需要获取到一份父类型的原型对象中的属性和方法。

能不能直接让子类型的原型对象 = 父类型的原型对象呢?

不要这么做, 因为这么做意味着以后修改了子类型原型对象的某个引用类型的时候, 父类型原生对象的引用类型也会被修改。

我们使用前面的寄生式思想就可以了。

创建原型对象的方法

javascript
// 工具函数
// 创建对象的过程
function createObject(o) {
    function F() {}
    F.prototype = o
    return new F()
}

// 将Subtype和Supertype联系在一起
// 寄生式函数
function inherit(Subtype, Supertype) {
    Subtype.prototype = createObject(Supertype.prototype)
    Object.defineProperty(Subtype.prototype, "constructor", {
        enumerable: false,
        configurable: true,
        writable: true,
        value: Subtype
    })
}

/*
    满足什么条件:
      1.必须创建出来一个对象
      2.这个对象的隐式原型必须指向父类的显式原型
      3.将这个对象赋值给子类的显式原型
*/
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 = Person.prototype

// 3.方案二:
// function F() {}
// F.prototype = Person.prototype
// Student.prototype = new F()

// 4.方案三:
var obj = Object.create(Person.prototype)
console.log(obj.__proto__ === Person.prototype)
Student.prototype = obj

寄生组合式继承 最终继承方案

js/inherit_utils.js

javascript
// 创建对象的过程
function createObject(o) {
  function F() {}
  F.prototype = o
  return new F()
}

// 将Subtype和Supertype联系在一起
// 寄生式函数
function inherit(Subtype, Supertype) {
  // Subtype.prototype.__proto__ = Supertype.prototype
  // Object.setPrototypeOf(Subtype.prototype, Subtype.prototype)
  Subtype.prototype = createObject(Supertype.prototype)
  Object.defineProperty(Subtype.prototype, "constructor", {
    enumerable: false,
    configurable: true,
    writable: true,
    value: Subtype
  })
  // 让子类构造函数的隐式原型执行父类构造函数
  Object.setPrototypeOf(Subtype, Supertype) 
  // Subtype.__proto__ = Supertype
}
javascript
<script src="./js/inherit_utils.js"></script>
<script>
    // 寄生组合式继承
    // 原型链/借用/原型式(对象之间)/寄生式函数
    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("why", 18, 1.88, 111, 100)

</script>

原型-寄生式继承方案

道格拉斯最开始使用原型寄生式继承并不是用来实现类的继承,而是为了实现对象的继承。

javascript
// 对象之间的继承
// 默认的对象
var obj = {
    name: "why",
    age: 18
}

// 原型式继承
function createObject(o) {
    function F() {}
    F.prototype = o
    return new F()
}

// 寄生式函数
function createInfo(o, name, age, height, address) {
    var newObj = createObject(o)
    newObj.name = name
    newObj.age = age
    newObj.height = height
    newObj.address = address

    return newObj
}

// 创建另外一个对象, 这个对象可以继承自obj
// var info1 = createObject(obj)  
// info1.height = 1.88
// info1.address = "广州市"

// var info2 = createObject(obj)  
// info1.height = 1.88
// info1.address = "广州市"

// var info3 = createObject(obj)  
// info1.height = 1.88
// info1.address = "广州市"

// 创建一系列对象
var info1 = createInfo(obj, "why", 18, 1.88, "广州市")
var info2 = createInfo(obj, "kobe", 30, 1.98, "洛杉矶市")

Object是所有类的父类

从我们上面的Object原型我们可以得出一个结论:原型链最顶层的原型对象就是Object的原型对象

javascript
<script src="./js/inherit_utils.js"></script>
<script>

function Person() {}
function Student() {}
function Teacher() {}

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

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

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

// 函数对象也是最终继承自Object
function foo() {}
console.log(foo.message) // coderwhy

</script>

对象的方法补充

hasOwnProperty

对象是否有某一个属于自己的属性(不是在原型上的属性)

in/for in 操作符

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

instanceof

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

isPrototypeOf

用于检测某个对象,是否出现在某个实例对象的原型链上

javascript
<script src="./js/inherit_utils.js"></script>
<script>

    var obj = {
        name: "why",
        age: 18
    }

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) // true
console.log("address" in info) // true
// 注意: for in遍历不仅仅是自己对象上的内容, 也包括原型对象上的内容
for (var key in info) {
    console.log(key) // name age address intro
}

// 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

</script>

原型继承关系

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

function foo() {} // new Function()
console.log(foo.length, foo.name)
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)

image-20230105232739526