• 技术文章 >web前端 >js教程

    javascript原型和继承是面试必会的

    coldplay.xixicoldplay.xixi2020-12-01 17:40:41转载1693

    javascript栏目介绍面试必会的原型和继承

    相关免费学习推荐:javascript(视频)

    本文从以下几个方面着手

    0 怎么理解面向对象

    其实我也不知道咋回答这问题,我只知道,面试官问这个后,就表示他要问一堆继承的问题了。下面是引用周老师的一段说辞。

    "面向对象是一种编程思想 与面向过程是对应的 一般的语言都是面向对象的 js本身也是基于面向对象构建出来的 ,例如 js本身就有很多内置类,Promise就是,可以new Promise来创建一个实例,来管理异步编程 。 还有vue 也是,平时都是创建vue的实例啊。"

    1 创建对象的方式

    1.对象字面量

    var o1 = {name: 'o1'}
    var o2 = new Object({name: 'o2'})

    2.通过构造函数

    var M = function(name){
        this.name = name
    }
    var o3 = new M('o3')

    3.Object.create

    var o4 = Object.create(p)

    2 记住原型链的小窍门

    记忆总是有规律的,如高中时期学的三角函数,需要背公式很多,强行去背全部的公式是容易混乱的。不过如果把核心的几点背牢,其余的公式只需要稍加推导即可。关于原型链也是一样,有几点在最开始就记住的话,后面就不会乱了。原型链中关键概念:构造函数实例constructor__ proto__prototype, 首先要记住他们的关系

    上面3点请先牢记,后面所总结的完整继承和这有紧密的关联

    其实 构造函数实例constructor__ proto__prototype 的关系已经在上面的例子和3点介绍中介绍完了。不妨再回顾一下

    1. 构造函数即普通函数,只不过前边有 new 关键字

    2. 通过 new构造函数 ,生成的对象即为实例。

    3. 以上面生成o3实例为例子

       o3.__proto__ === M.prototype  //true
      
       o3.prototype   //undefined
      
       o3.__proto__ === M.prototype //true
    4. o3实例本身并无constructor,不过会借助原型链向上查找,即,

       o3.constructor === M.prototype.constructor  // true
      
       o3.constructor === M //true

    小结 理清这几个关键词的关系后,原型链就明朗很多了

    3 instanceof 模拟实现

    instanceof 的原理是什么呢? 先来看一下使用

    [] instanceof Array  // true

    即左边是对象,右边是类型,instanceof 就是要判断右边类型的prototype,是否在左边实例的原型链上,如下例子所示

    [].__proto__ === Array.prototype //true
    Array.prototype.__proto__ === Object.prototype //true
    Object.prototype__proto__ //null

    那么依据这个思想来实现一下instanceof吧,一定会印象更加深刻

    function myInstanceof2(left, right){
        if(left === null || left === undefined){
            return false
        }
        if(right.prototype === left.__proto__) {
            return true
        }
    
        left = left.__proto__
        return myInstanceof2(left, right)
    }
    
    console.log(myInstanceof2([], Array))

    4 new 模拟实现(简要版)

    new的过程发生了什么?

    1. 生成空对象

    2. 这个空对象的proto赋值为构造函数的prototype

    3. 绑定this指向

    4. 返回这个对象

       // 构造函数
       function M(name){
          this.name = name
       }
       // 原生new
       var obj = new M('123')
      
       // 模拟实现
       function create() {
         // 生成空对象
         let obj = {}
         // 拿到传进来参数的第一项,并改变参数类数组
         let Con = [].shift.call(arguments)
         // 对空对象的原型指向赋值
         obj.__proto__ = Con.prototype
         // 绑定this 
         //(对应下面使用来说明:Con是参数第一项M,
         // arguments是参数['123'],
         // 就是 M方法执行,参数是'123',执行这个函数的this是obj)
         let result = Con.apply(obj, arguments)
         return result instanceof Object ? result : obj
       }
      
       var testObj = create(M, '123')
       console.log('testObj', testObj)

    5 继承的实现(逐步实现)

    一步一步来,从简到繁,更能直观发现继承的原理与缺点

    1. 构造方法方式 核心 Parent1.call(this)

       // 构造方法方式
       function Parent1(){
          this.name = 'Parent1'
       }
       Parent1.prototype.say = function () {
          alert('say')
       }
       function Child1(){
          Parent1.call(this)
          this.type = 'type'
       }
      
       var c1 = new Child1()
       c1.say() //报错

    缺点: 只能继承父类构造函数内部属性,无法继承父类构造函数原型对象上属性

    思考: 为什么 call 实现了继承,call本质是什么?

    1. 只借助原型继承 核心 Child2.prototype = new Parent2()

       // 原型
       function Parent2(){
          this.name = 'Parent2'
          this.arr = [1,2]
       }
       Parent2.prototype.say = function () {
          alert('say')
       }
       function Child2(){
          // Parent2.call(this)
          this.type = 'type'
       }
       Child2.prototype = new Parent2()
      
       var c21 = new Child2()
       var c22 = new Child2()
      
       c21.say()
       c21.arr.push('9')
       console.log('c21.arr : ', c21.arr)
       console.log('c22.arr : ', c22.arr)

    缺点: c21.arr 与c22.arr对应的是同一个引用

    思考:为什么这么写是同一个引用?

    1. 组合继承1

    把上面两个继承方式的优点合并起来,缺点都抛弃掉

     function Parent3(){
        this.name = 'Parent3'
        this.arr = [1,2]
    }
    Parent3.prototype.say = function () {
        alert('say')
    }
    function Child3(){
        Parent3.call(this)
        this.type = 'type'
    }
    Child3.prototype = new Parent3()
    
    var c31 = new Child3()
    var c32 = new Child3()
    
    c31.say()
    c31.arr.push('9')
    console.log('c31.arr : ', c31.arr)
    console.log('c31.arr : ', c32.arr)

    思考: 这么写就没有问题了吗?

    答 : 生成一个实例要执行 Parent3.call(this) , new Child3(),也就是Parent3执行了两遍。

    1. 组合继承2

    改变上例子 的

      Child3.prototype = new Parent3()

      Child3.prototype = Parent3.prototype

    缺点 : 很明显,无法定义子类构造函数原型私有的方法

    1. 组合继承优化3 再次改变上例子 的

      Child3.prototype = Parent3.prototype

       Child3.prototype = Object.create(Parent3.prototype)

    问题就都解决了。 因为Object.create的原理是:生成一个对象,这个对象的proto, 指向所传的参数。

    思考 :是否还有疏漏?一时想不起来的话,可以看下这几个结果

    console.log(c31 instanceof Child3) // true
    console.log(c31 instanceof Parent3) // true
    console.log(c31.constructor === Child3) // false
    console.log(c31.constructor === Parent3) // true

    所以回想起文章开头所说的那几个需要牢记的点,就需要重新赋值一下子类构造函数的constructor: Child3.prototype.constructor = Child3,完整版如下

    function Parent3(){
        this.name = 'Parent3'
        this.arr = [1,2]
    }
    Parent3.prototype.say = function () {
        alert('say')
    }
    function Child3(){
        Parent3.call(this)
        this.type = 'type'
    }
    
    Child3.prototype = Object.create(Parent3.prototype)
    Child3.prototype.constructor = Child3
    
    var c31 = new Child3()
    var c32 = new Child3()
    
    c31.say()
    c31.arr.push('9')
    console.log('c31.arr : ', c31.arr)
    console.log('c31.arr : ', c32.arr)
    
    console.log('c31 instanceof Child3 : ', c31 instanceof Child3)
    console.log('c31 instanceof Parent3 : ', c31 instanceof Parent3)
    console.log('c31.constructor === Child3 : ', c31.constructor === Child3)
    console.log('c31.constructor === Parent3 : ', c31.constructor === Parent3)

    5 es6的继承

    class Parent{
      constructor(name) {
        this.name = name
      }
      getName(){
        return this.name
      }
    }
    
    class Child{
      constructor(age) {
        this.age = age
      }
      getAge(){
        return this.age
      }
    }

    es6继承记住几个注意事项吧

    a30e44755e7e46f326f756d54c203d0.png


    <figcaption></figcaption>

    注意写了extends关键字,constructor中就必须写super(),打印结果如下:

    a30e44755e7e46f326f756d54c203d0.png

    以上就是javascript原型和继承是面试必会的的详细内容,更多请关注php中文网其它相关文章!

    声明:本文转载于:简书,如有侵犯,请联系admin@php.cn删除
    上一篇:了解Node.js中的process对象 下一篇:Angular中怎么导出表格Excel表格?
    大前端线上培训班

    相关文章推荐

    • 使用这8个javascript库,可以更好地处理本地存储!!• 了解javascript中3种for循环风格以及何时使用它们• 详解使用 JavaScript 解析 URL的方法• 浅谈JavaScript中工厂函数和构造函数

    全部评论我要评论

  • 取消发布评论发送
  • 1/1

    PHP中文网