前端面试宝典---原型链

引言----感谢大佬的讲解

大佬链接

原型链示意图

原型链问题中需要记住一句话:一切变量和函数都可以并且只能通过__proto__去找它所在原型链上的属性与方法

原型链需要注意的点

看上图可以发现

  1. 函数(构造函数)也可以通过__proto__去找到原型对象也就是Function.prototype
  2. Function.__proto__ === Function.prototype

练习题

typescript 复制代码
function Test(name, age){
    this.name = name
    this.age = age
}
var obj = new Test('Jack', 26)
 
Object.prototype.price = 2000
 
Function.prototype.price = 300
 
console.log(Test.price) // 300
console.log(obj.price) // 2000

原型链继承的方式

typescript 复制代码
function Person (name, age) {
  this.name = name
  this.age = age
}

// person的子类
function Student (name, age, score) {
  Person.call(this, name, age)
  this.score = score
}
// 1. 根据原型创建一个空对象
Student.prototype = Object.create(Person.prototype) // Object.create(Person.prototype)创建的对象是一个以Person.prototype为原型的对象
// 2. 修改Student的prototype的constructor
Student.prototype.constructor = Student // 继承
// 3.更新tostring方法
Student.prototype[Symbol.toStringTag] = Student.name

let s1 = new Student('wangwu', 18, 100)
console.log('s1.__proto__', s1.__proto__)
console.log('s1.__proto__.__proto__', s1.__proto__.__proto__)
console.log('Person.prototype', Person.prototype)
console.log('Object.prototype.toString.call(s1)', Object.prototype.toString.call(s1));
相关推荐
不好听61329 分钟前
JavaScript 到底是怎么运行的?从编译阶段到执行上下文全面解析
javascript
丷丩1 小时前
MapLibre GL JS第29课:添加Canvas源
javascript·gis·map·mapbox·maplibre gl js
就叫_这个吧1 小时前
HTML常用标签及举例使用
前端·html
utf8mb4安全女神1 小时前
【rsyslog服务】把所有服务的“临界点”以上的错误都保存在/var/log/alert.log⽇志中
java·前端·javascript
YANQ6621 小时前
7.bundlesdf本地安装
前端·webpack·node.js
csdn_aspnet1 小时前
javascript 算法 LeetCode 编号 70 - 爬楼梯
开发语言·javascript·算法·leetcode·ecmascript
swipe1 小时前
DeepAgents 多 Agent 深度调研助手工程实战:从 createDeepAgent 到可控调研工作流
javascript·面试·langchain
星夜夏空991 小时前
FreeRTOS学习(7)——任务列表
java·前端·学习
moMo2 小时前
JavaScript 变量提升,执行上下文里的各种门道
javascript·面试
weixin_471383032 小时前
由浅入深递归练习
前端·javascript·vue.js