原型链一直是前端避不开的坎,虽然工作中根本用不上,但是面试的时候,为了突出水平,面试官都是会问的。今天要分享一下我在学习原型链的时候,发现的一个奇葩东西(需要有原型链的基础才继续看哦~)
这张原型图想必大家应该都见过吧,如果不懂的话,建议先看下:《这篇文章》
咱们先把需要的变量声明一下
function Person(name, age) {
this.name = name
this.age = age
}
Person.prototype.sayName = function() {
console.log(`我是${name}, 我今年${age}岁`)
}
const person1 = new Person('颜少连',888);
const person2 = new Object();
const person3Father = new Function('name', 'age', 'console.log(`我是${name}, 我今年${age}岁`)');
观察第一个图,细心的同学应该发现了,Function
的实例person3Father
和 Person()
还有Object()
指向了同一个地方————Function.prototype
那?person3Father
是不是也具备当构造函数的功能呢?
// 我们先打印一下Person , Object , Function , person1 , person2 , person3Father的类型
console.log(typeof Person(),typeof Object(),typeof Function(),typeof person1,typeof person2,typeof person3Father)
// result in:function function function object object function
person3Father
果然为function
这就意味着不仅具备实例的特性,而且具备构造函数的特性?
//实例都是具有隐式原型指向(__proto__)
//而构造函数才有显示指向(prototype)
//我们打印一下三个实例的prototype
console.log(person1.prototype,person2.prototype,person3Father.prototype)
result in : undefined undefined {constructor: ƒ}
// 于是对person3Father进行实例声明
const person3Son = new person3Father('颜少连',8);
// result in :我是颜少连, 我今年8岁
实例化成功了,并且立马执行了原型的函数,打印出了: 我是颜少连, 我今年8岁
,为什么会执行了呢?
// 我们打印一下 person3Father.prototype
console.log(person3Father.prototype)
// 从下面这图可以知道,person3Father 的原型指向一个 anonymous(不知名的) 立即执行函数,
// 所以我们实例化的时候才会立即执行了函数
那实例化的 person3Son
又是什么呢,原型又指向了哪里?
console.log(person3Son);
// result in:{} 是一个空对象
console.log(person3Son.__proto__ === person3Father.prototype);
// result in : true
说明 person3Son
还是遵守原型规则的,不过,person3Father
和 person3Son
这个不知名的立即执行函数的原型的最终归宿又是怎样的?
console.log(person3Father.__proto__ === Object.__proto__)
// result in :true
console.log(person3Son.__proto__.__proto__)
// result in : fn Object 但是,这个Object并不指向 function Object()
console.log(person3Son.__proto__.__proto__ === Object) //false
console.log(person3Son.__proto__.__proto__.__proto__)
// result in : null
把所得的结果都拼接上去,就是下面这个图啦。person3Father
对 person1
和 person2
说,我既可以和你们当兄弟,还能当你们叔叔,笑嘻嘻的。
结语
如果你觉得此文对你有一丁点帮助,点个赞,给我一点儿鼓励哈~
其他有趣文章的传送门:
- 一篇学会Array原型里的所有方法
- 一篇掌握Object原型里的所有方法
- 初识Vue3,带你认识Vue2和Vue3的区别(一)
- vue图片放大器,相册集:vue-photo-preview
- 手摸手教你从0用echart写一个响应式页面