用图说话:prototype、__proto__与原型链的关系

43 阅读1分钟

一。普通对象

每个对象(object)都有一个私有属性(称之为 proto )指向它的构造函数的原型对象prototype,

obj.proto===Object.prototype

Object 对象,是一个构造函数,所以对象Object.constructor=== Function

任何原型对象都有个constructors属性,constructor指向该方法(函数)本身

obj.constructor ===Object

Object.constructor ===Function

Function.constructor ===Function

Object.prototype.constructor ===Object

image.png

二。构造函数出来的对象

function Stundent(name) { this.name = name } 
let person = new Stundent("linxi")

构造出来的对象的私有属性(称之为 proto )指向构造他的函数的原型对象,即 

person.proto === Stundent.prototype,

任何原型对象都有个constructors属性,constructor指向该方法(函数)本身

person.constructor === Stundent

Stundent.prototype.constructor === Stundent,

Stundent.constructor === Function

1701070535968.png

三。原型链

function Stundent(name) {
        // this.name = name
    }

    let person = new Stundent("linxi")
    // person.name = "person.name"
    person.__proto__.name = "person.__proto"

    // Stundent.prototype.name = "Stundent_prtotype"
    Object.prototype.name = "Object.prototype"
    Stundent.prototype.__proto__.name = 'Stundent.prototype.__proto__'



    console.log('person', person, person.name, Object.prototype.__proto__)

person._proto=== Stundent.prototype

Stundent.prototype.proto === Object.prototype

Object.prototype.proto=null

上面的例子:通过打印出来的结果,一次次去掉显示结果的那一行可以得出请求是顺序

person.name---->Stundent里面的this.name----->Stundent.prototype------>person.proto------>Stundent.prototype.proto---------->

Object.prototype----->Stundent.prototype.proto.__proto__是null(就是Object.prototype.proto=null)

总结:原型链的顺序是:对象的属性值--》构造函数的属性值---》构造函数原型---》对象的私有原型--》构造函数私有原型--》对象原型----》原型链最顶端Object.prototype._proto_是null