Skip to content

原型原型链

🕒 Published at:

一、原型prototype和__proto__

  • 每个对象都有一个__proto__属性,并且指向它的构造函数的prototype原型对象。
  • 每个构造函数都有一个prototype原型对象
    • prototype原型对象的constructor指向构造函数本身

对象是引用数据类型,对象中的__proto__属性中实际上是保存的构造函数的prototype的指针地址。

实例对象的__proto__指向构造函数的prototype,从而实现继承。

通过代码来验证:

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

Person.prototype.sayName = function(){
    console.log(this.name)
}

let p1 = new Person('dong', 12)

p1.__proto__ === Person.prototype //true

p1.sayName() //dong
function Person(name ,age) {
    this.name = name
    this.age = age
}

Person.prototype.sayName = function(){
    console.log(this.name)
}

let p1 = new Person('dong', 12)

p1.__proto__ === Person.prototype //true

p1.sayName() //dong

二、原型链

javascript
let arr = ['xi', 'ha']

arr.valueOf() // ['xi', 'ha']
let arr = ['xi', 'ha']

arr.valueOf() // ['xi', 'ha']

这里并没有给arr的原型定义valueOf属性,但是它是可以在arr上找到该属性的,这是因为原型链的效果。

当试图访问对象的一个属性时,它不仅仅在该对象上搜索,也会在该对象的原型上进行查找,以及原型上的原型,依次搜索,直到找到该对象,或者到达原型链的尾端为止。

javascript
arr.__proto__ === Array.prototype //true

Array.prototype.__proto__ === Object.prototype //true

arr.__proto__.__proto__ === Object.prototype //true

Object.prototype.__proto__ === null //true
arr.__proto__ === Array.prototype //true

Array.prototype.__proto__ === Object.prototype //true

arr.__proto__.__proto__ === Object.prototype //true

Object.prototype.__proto__ === null //true

查找过程:

arr --> Array.prototype --> Object.prototype  --> null
arr --> Array.prototype --> Object.prototype  --> null
--- Done ---