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()//旅行
    
    
  • 相关阅读:
    运行monkeyrunner脚本
    Monkey
    ubuntu下在Eclipse中配置MonkeyRunner环境
    ubuntu下Gradle离线安装
    ubuntu下反编译apk
    PuTTY 设置Serial(ubuntu)
    工作中接触的命令
    自动化功能测试(QTP)汉化12.0
    App测试工作
    vue项目在vscode中编译eslint报错没显示红色波浪线提示
  • 原文地址:https://www.cnblogs.com/zshno1/p/14075949.html
Copyright © 2011-2022 走看看