js原型知識梳理(二)

最近從新梳理了一下原型的知識,想分享一下,但願對那些被原型,原型鏈,構造函數,實例對象等關係滿頭包的童鞋有些幫助~~~
廢話不說了 上代碼函數

//原型 prototype
        function Man(name,age){
            this.name=name,
            this.age=age
        }
        let Person={
            name:'李四',
            age:18,
            hobby:'reading',
            //...
        }
        Man.prototype=Person  //這裏 Person 就是Man的原型 
        //原型是指構造函數經過prototype訪問的屬性

        let boy=new Man() //boy爲Man的實例對象 
        //boy是Man這個構造函數實例化出來的對象
        console.log(boy)

這是boy的打印結果
image.pngthis

再打印一下 boy.__proto__ 咱們能夠看到boy的__proto__是Man的原型 Person對象spa

image.png

console.log(boy.__proto__==Man.prototype)// true 
//boy這個實例化對象的原型和Man的原型指向同一個對象`

繼續打印 boy._proto_._proto_和boy._proto_._proto_._proto_prototype

console.log(boy.__proto__.__proto__)//Object
//能夠看到boy的原型的原型是Object對象,再往上找爲空
        console.log(boy.__proto__.__proto__.__proto__)//null
        //這種經過_proto_逐層向上訪問的鏈式關係稱爲原型鏈

image.png

下面是原型,原型鏈,構造函數的關係圖
咱們能夠看到,原型鏈就是經過_proto_鏈接的鏈式繼承關係3d

image.png

相關文章
相關標籤/搜索