zoukankan      html  css  js  c++  java
  • js实现模拟继承的方法

    1.通过拓展Object类的原型对象实现继承

        function Parent(name,age,ID,address){

        this.name = name;
    this.age = age;
    this.id = ID;
    this.address = address;
    }

    function Child(school){
    this.school = school;
    }
    Object.prototype.extend = function(parentObj){
    for(var i in parentObj){
    this[i] = parentObj[i];
    }
    };

    var parent = new Parent("小明","24","10001","福山");
    var child = new Child("长江大学");
    child.extend(parent);//子类继承父类
    console.log(child.age);

    2.通过call方法改变指针指向实现继承
    //call无参的
    function parent2(){
    this.name = "zhangsan";
    this.age = 20;
    }
    function child2(){
    console.log(this.name+" "+this.age);
    }
    var p = new parent2();

    //child2();//window对象调用该方法
    //p.show();//写法错误,因为p对象没有show方法
    child2.call(p);//这种写法可以实现让show方法里的this指向p对象


    //call有参的
    function parent3(){
    this.name = "zhangsan";
    this.age = 20;
    }
    function child3(school){
    console.log(this.name+" "+this.age+":"+school);
    }
    var p1 = new parent3();
    child3.call(p1,"长江大学");//这种写法可以实现让show方法里的this指向p对象
     
    3.通过apply方法改变指针指向实现继承

    //apply无参的
    function parent4(){
    this.name = "xiaohong";
    this.age = 25;
    }
    function child4(){
    console.log(this.name+" "+this.age);
    }
    var p2 = new parent4;
    child4.apply(p2);

    //apply有参的
    function parent5(){
    this.name = "xiaohong";
    this.age = 25;
    }
    function child5(school){
    console.log(this.name+" "+this.age+" "+school);
    }
    var p3 = new parent5;
    child5.apply(p3,['长江大学']);


    4.通过改变对象的prototype方法实现继承

    function Parent6(address,net,no){
    this.add = address;
    this.net = net;
    this.no = no;
    }
    function Child6(school,teacher){
    this.school = school;
    this.teacher = teacher;
    }
    Child6.prototype = new Parent6("迎春大街","www.jerui.com","1608");
    var child6 = new Child6();
    console.log(child6.add);
     



  • 相关阅读:
    sizeof和strlen与带汉字字符的
    PS常用工具
    色彩原理和图层混合模式
    文字工具和栅格化
    CreateWaitableTimer和SetWaitableTimer函数(定时器)
    FMod终结篇
    理财达人五步走
    C++中的Union
    关于对于VCMFCATL的评论问题
    FMOD 快速上手
  • 原文地址:https://www.cnblogs.com/chencuixin/p/6485533.html
Copyright © 2011-2022 走看看