zoukankan      html  css  js  c++  java
  • js实现继承的几种方式

    1 构造函数 

    function SuperType() {
    this.colors = ["red","blue","green"];
    }
    function SubType() {
    SuperType.call(this);//继承了SuperType
    }

    2 原型链

     

    function SuperType() {
    this.property = true;
    }
    SuperType.prototype.getSuperValue = function() {
    return this.property;
    }
    function subType() {
    this.property = false;
    }
    //继承了SuperType
    SubType.prototype = new SuperType();
    SubType.prototype.getSubValue = function (){
    return this.property;
    }
    var instance = new SubType();
    console.log(instance.getSuperValue());//true
    

    3 组合继承

    function SuperType(name) {
    this.name = name;
    this.colors = ["red","blue","green"];
    }
    SuperType.prototype.sayName = function() {
    console.log(this.name);
    }
    function SubType(name, age) {
    SuperType.call(this,name);//继承属性
    this.age = age;
    }
    //继承方法
    SubType.prototype = new SuperType();
    Subtype.prototype.constructor = Subtype;
    Subtype.prototype.sayAge = function() {
    console.log(this.age);
    }
    var instance1 = new SubType("EvanChen",18);
    instance1.colors.push("black");
    consol.log(instance1.colors);//"red","blue","green","black"
    instance1.sayName();//"EvanChen"
    instance1.sayAge();//18
    var instance2 = new SubType("EvanChen666",20);
    console.log(instance2.colors);//"red","blue","green"
    instance2.sayName();//"EvanChen666"
    instance2.sayAge();//20

    4 原型式继承

    var person = {
    name:"EvanChen",
    friends:["Shelby","Court","Van"];
    };
    var anotherPerson = Object.create(person);
    anotherPerson.name = "Greg";
    anotherPerson.friends.push("Rob");
    var yetAnotherPerson = Object.create(person);
    yetAnotherPerson.name = "Linda";
    yetAnotherPerson.friends.push("Barbie");
    console.log(person.friends);//"Shelby","Court","Van","Rob","Barbie"

    5 寄生式继承

    function createAnother(original) {
    var clone = Object.create(original);
    clone.sayHi = function () {
    alert("hi");
    };
    return clone;
    }
    var person = {
    name:"EvanChen",
    friends:["Shelby","Court","Van"]
    };
    var anotherPerson = createAnother(person);
    anotherPerson.sayHi();///"hi"

    6 寄生组合式继承

    function SuperType(name){
    this.name = name;
    this.colors = ["red","blue","green"];
    }
    SuperType.prototype.sayName = function (){
    alert(this.name);
    };
    function SubType(name,age){
    SuperType.call(this,name);
    this.age = age;
    }
    inheritProperty(SubType,SuperType);
    SubType.prototype.sayAge = function() {
    alert(this.age);
    }
  • 相关阅读:
    IPV6地址中的%号什么意思
    比较分析C++、Java、Python、R语言的面向对象特征,这些特征如何实现的?有什么相同点?
    Linux 查看本机串口方法
    非对称加密与GPG/PGP
    bootstrap下拉三角
    bootstrap文本背景色
    bootstrap文本颜色
    bootstrap栅格系统响应式
    软件测试(一) 软件测试的阶段划分
    YoTube 视频如何下载
  • 原文地址:https://www.cnblogs.com/love-yangerlei/p/8252076.html
Copyright © 2011-2022 走看看