zoukankan      html  css  js  c++  java
  • js继承再解析

    之前学习过一段时间js继承,当时以为懂了(其实没懂),现在拿出来在回味复习一下~

    参考了这篇文章: http://www.cnblogs.com/ayqy/p/4471638.html

    js的继承 一共六种方式,可以参考【js高程三】

    本文直接 用图描述了一遍 四.寄生组合继承(最佳方式)

    function beget(obj){   // 生孩子函数 beget:龙beget龙,凤beget凤。
        var F = function(){};
        F.prototype = obj;
        return new F();
    }
    function Super(){
        // 只在此处声明基本属性和引用属性
        this.val = 1;
        this.arr = [1];
    }
    //  在此处声明函数
    Super.prototype.fun1 = function(){};
    Super.prototype.fun2 = function(){};
    //Super.prototype.fun3...
    function Sub(){
        Super.call(this);   // 核心
        // ...
    }
    console.log(Super.prototype)
    var proto = beget(Super.prototype); // 核心
    var proto2 = Super.prototype; // 核心
    proto.constructor = Sub;            // 核心
    Sub.prototype = proto;              // 核心
    
    console.log(Super.prototype)
    
    var sub = new Sub();
    console.log(sub);
    console.log(Sub);
    

    其中有一个问题 Sub要继承Super为什么要通过一个F呢?

    我们直接让 Sub 的 prototype = Super 的 prototype 会有什么影响?

    原因有两点

    • 我们如果要向Sub 的 prototype 上添加新函数时候 如果按照刚才的假设*(Sub 的 prototype = Super 的 prototype) 那这个函数会添加到Super.prototype上,

    • 关于constructror 如果按照刚才的假设(Sub 的 prototype = Super 的 prototype) proto其实指向的是 Super,而不是我们希望的 Sub

  • 相关阅读:
    Median of Two Sorted Arrays
    Two Sum
    C# Socket服务端和客户端互相send和receive
    C++ 虚函数和虚函数表
    C++ 类型转换
    C# 几种退出程序的方式
    进程判断及简单操作
    C#根据函数名称执行对应的函数
    C# DateTime格式化
    nginx常用代理配置
  • 原文地址:https://www.cnblogs.com/WhiteHorseIsNotHorse/p/7422880.html
Copyright © 2011-2022 走看看