zoukankan      html  css  js  c++  java
  • 继承的三种方式

    //对象冒充方式继承(支持多继承) 
    function ClassA(sColor) {
    this.color = sColor;
    this.sayColor = function () {
    console.log(this.color);
    };
    }
    var a = new ClassA("yellow");
    function ClassB() {
    ClassA.call(this,"blue");
    this.ll = "hh";
    this.say = function(){
    console.log(this.ll);
    }
    }
    var b = new ClassB();
    var c = new ClassB();

    console.log(b.sayColor === c.sayColor);//false这说明每一个对象都保存了一份sayColor函数的代码体(体现函数 逻辑的数据)
    //的副本,显然是一种浪费


    //原型方式继承(不支持多继承)
    function ClassA() { }
    ClassA.prototype.color = "blue";
    ClassA.prototype.sayColor = function () {
    alert(this.color);
    };
    function ClassB() { }
    ClassB.prototype = new ClassA();
    ClassB.prototype.name = "";
    ClassB.prototype.sayName = function () {
    alert(this.name);
    };
    var a= new ClassA();
    var b= new ClassB();
    var c = new ClassB();
    console.log(b.sayColor === c.sayColor);//true共享同一份方法
    console.log(b.sayColor === a.sayColor);//true
    console.log(b.sayName === c.sayName);//true
    console.log(b.color === c.color);//true


    //混合方式(创建类的最好方式是用构造函数定义属性,用原型定义方法) //用对象冒充继承构造函数的属性,用原型链继承 prototype 对象的方法
    function ClassA(sColor) {
    this.color = sColor;
    }
    ClassA.prototype.sayColor = function () {
    alert(this.color);
    };
    function ClassB(sColor, sName) {
    ClassA.call(this, sColor);
    this.name = sName;
    }
    ClassB.prototype = new ClassA();
    ClassB.prototype.sayName = function () {
    alert(this.name);
    };
    var b = new ClassB("black","kk");
    var c = new ClassB("red","ll");
  • 相关阅读:
    VMware Workstation CentOS7 Linux 学习之路(2)--.net core环境安装
    VMware Workstation CentOS7 Linux 学习之路(1)--系统安装
    Castle IOC概念理解
    Visual Studio Nuget还原步骤
    Js中分号使用总结
    ABP理论学习之依赖注入
    C# 中字段和属性的使用时机
    C#基础知识梳理系列
    .Net 中的IL中间语言基本语法
    项目工程结构说明(Internal)
  • 原文地址:https://www.cnblogs.com/huahua-1022/p/7120150.html
Copyright © 2011-2022 走看看