原型和原型链详解

定义

原型:prototype,就是函数的一个属性而已,对象形式;

原型链:__proto__,保存着该对象构造函数prototype,也可以理解为儿子的__proto__ 存放着 爸爸的prototype

示例

1
2
3
4
5
6
7
8
9
10
11
function Father() { }

Father.prototype.des = '我是爸爸'

const child = new Father()

console.log(`Father的prototype => `)
console.log(Father.prototype)
console.log('------------------------')
console.log(`child的__proto__ => `)
console.log(child.__proto__)

运行结果
可以看出两者是一样的,成功说明验证了 儿子的__proto__ 存放着 爸爸的prototype

再看一种情况,我们想知道Father的__proto__是什么,也就说生成Father的构造函数,它的prototype是什么

1
2
3
4
5
6
function Father() { }

Father.prototype.des = '我是爸爸'

console.log(`Father的__proto__ =>`)
console.log(Father.__proto__)

运行结果
为什么是native code?可以理解为生成Function的底层代码,底层代码经过一系列运行,生成了Father这个函数。也就是Function.prototype

我们再来看一种情况:

1
2
3
4
5
6
7
function Father() { }

Father.prototype.des = '我是爸爸'

const child = new Father()

console.log(child.des) //最终输出 我是爸爸

我们明明没有给child添加属性,为什么还能打印出des呢?

其实就是从child本身开始,一层一层向上找,只要上级存在des这个属性,那么都算这个链条上的属性,所以child.des有值;

想知道child里面到底有没有des属性

这时候就要使用Object.hasOwn()方法,可以理解为检测本身具体有没有一个属性;

1
2
3
4
5
6
7
function Father() { }

Father.prototype.des = '我是爸爸'

const child = new Father()

console.log(Object.hasOwn(child, 'des')) //最终输出 false,虽然原型链上面有,但是本身不存在,所以是false

原型和原型链详解
https://liujiaweb.cn/posts/41431.html
作者
Liu Jia
发布于
2020年7月18日
许可协议