zoukankan      html  css  js  c++  java
  • javaScript面向对象(继承篇)

     

    一、构造函数继承

     
    function Parent() {
      this.money = '2亿'
      this.eat = function () {
        console.log('吃饭')
      }
    }
    
    function Son(name, age) {
      Parent.apply(this, arguments)
      this.name = name;
      this.age = age
    
    }
    
    var s = new Son("小明", 18);
    s.eat()//吃饭

    二、prototype模式

    * 通过 子类的prototype = 父类的实例来继承
    * 缺点:效率比较低,比较废内存
     
    function Parent() {
      this.money = '2亿'
      this.eat = function () {
        console.log('吃饭')
      }
    }
    
    Parent.prototype.hobby = function () {
      console.log("旅行")
    }
    
    
    function Son(name, age) {
      this.name = name;
      this.age = age
    }
    
    
    Son.prototype = new Parent(); // 将Son的prototype对象指向一个Parent的实例。它相当于完全删除了prototype 对象原先的值,然后赋予一个新值
    /**
    *
    * 任何一个prototype对象都有一个constructor属性,指向它的构造函数。
    * 如果没有"Son.prototype = new Parent();"这一行,Son.prototype.constructor是指向Son的;加了这一行以后,Son.prototype.constructor指向Parent。
    *
    */
    Son.prototype.constructor = Son
    
    var son = new Son("小明", 18);
    son.hobby()//旅行
    
    


    三、直接继承prototype

    * 子类的prototype = 父类的prototype
    * 缺点:子类的prototype和父类的prototype指向同一个对象,那么子类的prototype修改那么父类的prototype也会修改
    function Parent() { }
    
    Parent.prototype.hobby = function () {
      console.log("旅行")
    }
    
    
    function Son(name, age) {
      this.name = name;
      this.age = age
    }
    
    Son.prototype = Parent.prototype;
    Son.prototype.constructor = Son;
    
    let s = new Son();
    s.hobby();//旅行
    
    


    四、利用空对象作为中介

    * 优点:空对象几乎不占内存,子类的prototype修改不会影响到父类prototype的改变
    function Parent() { }
    
    Parent.prototype.hobby = function () {
      console.log("旅行")
    }
    
    function Son(name, age) {
      this.name = name;
      this.age = age
    }
    
    // function Buffer(){} //空对象
    // Buffer.prototype = Parent.prototype;
    // Buffer.prototype.constructor = Buffer;
    // Son.prototype = new Buffer();
    // Son.prototype.constructor = Son;
    // let s = new Son();
    // s.hobby()
    
    /**
    * 对上述方法进行封装
    */
    
    function extend(Child, Parent) {
      function Buffer() { };
      Buffer.prototype = Parent.prototype;
      Buffer.prototype.constructor = Buffer;
      Child.prototype = new Buffer();
      Child.prototype.constructor = Child
    }
    
    extend(Son, Parent);
    let s = new Son();
    s.hobby()//旅行
    
    
  • 相关阅读:
    c语言进阶2-变量的作用域与无参函数
    《Linux 性能及调优指南》3.2 CPU瓶颈
    《Linux 性能及调优指南》3.1 确认瓶颈
    马哥Linux base学习笔记
    《Linux 性能及调优指南》1.6 了解Linux性能指标
    Linux性能及调优指南1.2之Linux内存架构
    《Linux 性能及调优指南》1.1 Linux进程管理
    分布式系统的Raft算法
    《马哥出品高薪linux运维教程》wingkeung学习笔记-linux基础入门课程
    Systemd 入门教程:实战篇
  • 原文地址:https://www.cnblogs.com/zshno1/p/14075949.html
Copyright © 2011-2022 走看看