zoukankan      html  css  js  c++  java
  • JS 类继承 原型继承

    参考文档:JS原型继承和类继承

    <script src="jquery-2.0.3.js">
    
    
    </script>
    <script>
    /*//类继承 
     var father=function(){
        this.age=53;
        this.say=function(){
            console.log("name:"+this.name+",age:"+this.age);
        }
     };
     var child=function(){
        this.name="child";
        father.call(this);
     }
     var man=new child();
     man.say();
    console.log(man);
    */ //原型继承 var father=function(){} father.prototype.a=function(){console.log(11)}; var child=function(){}; child.prototype=new father(); var man=new child(); man.a(); console.log(man); </script>

    类继承时打印man:

    原型继承时打印man:

     看似,原型继承时,对象可以调用原型上的方法

    类继承的方法,每一次都会存到内存中,损耗性能,并且不容易扩展

    原型继承:很灵活,改变原型链即可,写好extend就可以

    通常继承会汇聚两种方式的优点,组合模式就是这样做:用类继承去继承属性(每个实例的属性应该是私有的,不应该是共有的),用原型继承去继承方法

    例如

      var father=function(){
        this.age=53;
        
     };
     father.prototype.b=new function(){
        console.log(this.age);
     }
     var child=function(){
        
        father.call(this);
     }
    child.prototype=new father();
    var man=new child();
    console.log(man);

     **使用 Object.create()

    var father ={
        a:'father',
        b:function(){
            console.log(this.a);
        }
    }
    var obj=Object.create(father);
    console.dir(obj);

    有问题在公众号【清汤袭人】找我,时常冒出各种傻问题,然一通百通,其乐无穷,一起探讨


  • 相关阅读:
    博客园-随笔分类批量修改
    【读书笔记】--少有人走的路①:心智成熟的旅程
    自定义菜单用例
    自定义菜单创建接口
    发送消息---被动回复用户消息
    接收消息----接收语音识别结果
    接收消息----接收事件推送
    微信开发入门教程
    Hadoop维护IPC链接
    Hadoop建立IPC连接和数据读写
  • 原文地址:https://www.cnblogs.com/qingmaple/p/6165609.html
Copyright © 2011-2022 走看看