• Base Class 慎用箭头函数


    在项目中,child继承base的时候,需要重新修改base.fun的逻辑,但是有些情况下面并不是简单的覆盖,而是在base.fun的逻辑基础上进行加工处理。

    刚开始接触es6的时候也许都遇到过,child重写了base的fun函数,就是不起作用

          先来段正常的代码,看下面的逻辑,这段代码在chrome中可以直接运行

         

     1 class Base {
     2     static classMethod() {
     3         console.log('Base classMethod')
     4     }
     5     constructor() {
     6         this.key = 'Base';
     7         console.log('Base constructor')
     8     }
     9     fun() {
    10         console.log('Base fun')
    11     }
    12 }
    13 class Child extends Base {
    14     static classMethod() {
    15         super.classMethod();
    16         console.log('Child classMethod')
    17     }
    18     constructor() {
    19         super();
    20         this.key = 'Child';
    21         console.log('Child constructor')
    22     }
    23     fun() {
    24         super.fun();
    25         console.log('Child fun')
    26     }
    27 }
    28 new Child().fun();

       运行结果:

      

           但是我们常常会遇到,设计base的时候,fun是给组件事件使用的,需要通过箭头函数进行this绑定,所以就给base.fun加了个箭头函数。

           这个写法chrome不支持,需要借助babel转义,通过在线的https://babeljs.cn/repl/进行在线转下,在chrome进行运行

       

           运行结果:

      

            神奇的事情发生了,只打印了Base fun,那我们就需要仔细看下转义的代码。

      

      发现Base.fun在constructor的时候变成了this.fun,Child.fun在obj.__proto__.fun在原型链上,所以Base.fun的优先寻找到

          执行new Child().__proto__.fun()的时候也报错了,Base.prototype.fun也不存在了

      所以在写业务的时候,不需要考虑这些问题,如果说是写的基础类,组件类,就要慎用箭头函数了

  • 相关阅读:
    linux内核中创建线程方法
    高等数学所有符号的写法与读法
    Git学习笔记03--git reset
    git status message
    [小技巧] git: Your branch and 'origin/master' have diverged
    phalcon: 资源文件管 理 引入css,js
    phalcon: model 验证数据完整性
    phalcon:model 事件与事件管理器
    phalcon: 查找记录(Finding Records)可用的查询设置如下:
    phalcon count统计
  • 原文地址:https://www.cnblogs.com/legu/p/8423394.html
Copyright © 2020-2023  润新知