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

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

大佬链接

原型链示意图

原型链问题中需要记住一句话:一切变量和函数都可以并且只能通过__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));
相关推荐
IT_陈寒19 分钟前
Vite打包时的静态资源坑,我帮你踩过了
前端·人工智能·后端
默_笙2 小时前
🔥 让 AI 帮我写完整个 Next.js 博客:框架就是 AI 的"上下文 buff"
前端·javascript
牧艺2 小时前
登录页还在用渐变?我一口气做了 5 个能摸的背景动效:吹蒲公英、滴墨染水、点熔岩闷裂
前端·canvas·交互设计
陆枫Larry2 小时前
状态机简介
前端
陆枫Larry2 小时前
一次登录问题排查:接口没错,错的是旧业务逻辑
前端
小小小小宇3 小时前
大模型打分与采样原理,以及 Pi Agent 核心原理
前端
一位正在转型AI全栈的前端工程师3 小时前
AI 全栈学习之旅 -Week 5:RAG 知识库问答系统:从零到生产级部署的全栈实践总结
前端·python
光影少年3 小时前
react navite 安卓iOS 打包、签名、环境区分
前端·react native·react.js
coderCN3 小时前
Nodejs 第三十四章 数据库(表达式和函数、子查询和连表)
前端·node.js
ssshooter4 小时前
AI 时代你不能不知道的 git worktree
前端·后端·面试