zoukankan      html  css  js  c++  java
  • javascript 继承之拷贝,原型,类式

    // 拷贝继承,在子类内调用父类并修正this指向,再通过for in 拷贝父类的方法实现继承,具体实现如下代码 :
    function Tab(){//父类构造函数
    this.name='aaa';
    this.age=20;
    }
    Tab.prototype.init = function(){
    alert(this.name);
    };
    function Child(){//子类构造函数
    Tab.call(this);//在子类构造函数内调用父类,使子类继承父类的属性
    }

    for(var attr in Tab.prototype){//通过for in 拷贝父类原型上的方法
    Child.prototype[attr]=Tab.prototype[attr];
    }
    var child=new Child();
    var tab=new Tab();
    child.name="bbb";//这里我们修改了子类的属性,下面打印结果,修改了子类不会影响父类
    console.log(tab)
    console.log(child)

    console.log(child instanceof Tab);//false
    console.log(child instanceof Child);//true 看出,child的构造函数还是自己本身

    //原型继承,在子类的原型上继承父类的实例化对象 :

    var father=function(){
    this.name='aa';
    }
    father.prototype.a=function(){
    alert(this.name);
    }
    var child=function(){}

    var fa=new father();

    child.prototype=fa;//在子类的原型上继承父类这个对象

    var man=new child();
    man.name='bbb';
    fa.name="ccc";
    console.log(fa);
    console.log(man);//继承的属性和值在其原型链上
    alert(fa.name)//ccc
    alert(man.name)//bbb

    //类式继承,通过在子类的构造函数类调用父类的构造函数,使子类拥有父类的属性和方法,并通过call或apply改变this指向,来实现继承 : 

    var father=function(){
    this.name='aa';

    this.age=function(){alert(1)}
    }
    father.prototype.a=function(){
    alert(this.name);
    }
    var child=function(){
    father.call(this);
    }

    child.prototype=father.prototype;//继承父类的方法

    var f=new father();
    var c=new child();
    console.log(f);
    console.log(c);



  • 相关阅读:
    webservice理解
    什么是xmlschema
    web项目中的跨域问题解决方法
    浏览器的同源策略和跨域问题
    java中Scanner和random的用法
    mybatis的批量删除
    java中的异常理解
    事务回滚
    做人做事2个字:心、眼
    Linux下找不到so文件的解决办法
  • 原文地址:https://www.cnblogs.com/week-1/p/6553650.html
Copyright © 2011-2022 走看看