小帅の技术博客 小帅の技术博客
首页
  • 基础
  • 框架
  • 进阶
  • 工程化
  • NodeJS
  • 脚本
  • 拓展
  • 技术
  • 服务器
程序猿
关于
友链
  • 分类
  • 标签
  • 归档
GitHub

前端小帅

学而不思则罔,思而不学则殆
首页
  • 基础
  • 框架
  • 进阶
  • 工程化
  • NodeJS
  • 脚本
  • 拓展
  • 技术
  • 服务器
程序猿
关于
友链
  • 分类
  • 标签
  • 归档
GitHub
  • JavaScript

  • 面试

    • 内容梳理
    • 图片优化
    • 服务&网络
    • 浏览器
    • CSS盒模型、BFC、Grid布局
    • 原型、原型链、原型继承和类继承特点
      • 基本属性
      • 继承的方式
        • 一. 构造函数继承
        • 二. 原型链继承
      • 组合:构造函数+原型链
      • ES6 class extend
    • this剖析apply、call、bind
    • JS模块化
    • CSS布局
    • 网络

原型、原型链、原型继承和类继承特点

面试官:说说原型链和继承吧

# 基本属性

  1. proto

    • 是一个指向原型对象的指针
  2. prototype

    • 实例
  3. constructor

    • 指向创建它的构造函数

# 继承的方式

  • 继承的本质就是原型链。

# 一. 构造函数继承

function Parent(name){
   this.name=name
   console.log('name', this.name);
}
const Child=new Parent('你好')   //Parent.call(this)
// name 你好
1
2
3
4
5
6
  • 原理:通过内部改变this的指向。

  • 缺点:无法继承父的原型,即父的原型增加一个方法,无法被子继承。

    Parent.prototype.say = function () {};
    
    1
  • 创建构造函数 new 的过程

//伪代码表示
var a = new Parent("Li","Cherry");

new Parent{
    var obj = {};
    obj.__proto__ = Parent.prototype;
    var result = Parent.call(obj,"Li","Cherry");
    return typeof result === 'object'? result : obj;
}
1
2
3
4
5
6
7
8
9
  • 过程分析:
  1. 创建一个空对象 obj;
  2. 将新创建的空对象的隐式原型指向其构造函数的显示原型。
  3. 使用 call 改变 this 的指向
  4. 如果无返回值或者返回一个非对象值,则将 obj 返回作为新对象;如果返回值是一个新对象的话那么直接直接返回该对象。

# 二. 原型链继承

function Parent(){
   this.name='parent xx'
}
function Child(){
   this.type='child xx'
}
Child.prototype=new Parent()
//console.log(new Child()) 打印结果
// Child{
//    type:'child xx'
//    __proto__:Parent{
//       name:'parent xx'
//       __proto__:Object
//    }
// }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
  • 原理:每个函数都有prototype属性,构造函数也有这个属性,这个属性是一个对象。把Parent的实例赋值给了Child的prototye,实现继承

  • new Child.__proto__ === new Parent()的结果为true

  • 优点:Child 可以继承 Parent 的原型

  • 缺点:如果修改 child1实例的name属性,child2实例中的name属性也会跟着改变。

    let child1=new Child()
    let child2=new Child()
    child1.name='xx'
    console.log('child1',child1.name) //child1 xx
    console.log('child2',child2.name) //child2 xx
    
    1
    2
    3
    4
    5

# 组合:构造函数+原型链

function Parent(){
   this.name='parent xx'
   this.arr=[1,2,3]
}
function Child(){
   Parent.call(this)
   this.type='child type'
}
Child.prototype=new Parent()
let child1 = new Child();
let child2 = new Child();
child1.name = 'xx';
console.log('child1', child1.name); //child1 xx
console.log('child2', child2.name); //child2 parent xx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
  • 优点:可以解决之前两种问题,既可以继承父类原型的内容,也不会造成原型里属性的修改。
  • 缺点:执行了两次Parent构造

# ES6 class extend

主要理解ES5的方法

编辑
上次更新: 2024/04/15, 14:35:14
CSS盒模型、BFC、Grid布局
this剖析apply、call、bind

← CSS盒模型、BFC、Grid布局 this剖析apply、call、bind→

最近更新
01
说说call、apply、bind是如何改变this的
03-29
02
从输入 URL 到页面加载完成发生了什么?
03-29
03
JavaScript进阶—— new 的执行过程
03-26
更多文章>
sunss | © 2020.08-2024.04 浙ICP备2022002957号-1
载入天数... 载入时分秒...  |  总访问量 次
提供CDN加速/云存储服务
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式