zoukankan      html  css  js  c++  java
  • 面向对象之继承(类式继承)

    function Aaa(){
       this.name = '小明';
    }
    
    Aaa.prototype.showName = function(){
        alert(this.name);
    }
    
    
    function Bbb(){
    
    }
    
    Bbb.prototype = new Aaa();        //实现继承
    
    var b1 = new Bbb();
    
    alert(b1.name);   //‘小明’

    一句话实现继承,是不是感觉很酷,以后就用他,但是,别急,因为他还有很多问题。。。。我们来看一下

    console.log(b1.constractor);       //ƒ Aaa(){this.name = '小明';}

    我们首先看到构造constractor的指向不对了,我们修改指向

    Bbb.prototype.constructor = Bbb;

    除此之外还有一个很严重的问题,我们来看代码

    function Aaa(){
       this.name = [1,2,3];
    }
    
    Aaa.prototype.showName = function(){
        alert(this.name);
    }
    
    
    function Bbb(){
    
    }
    
    Bbb.prototype = new Aaa();        //实现继承
    Bbb.prototype.constructor = Bbb;
    
    var b1 = new Bbb();
    
    b1.name.push(4);
    
    var b2 = new Bbb();
    console.log(b2.name);     //[1,2,3,4]

    b2竟然找到了b1所push的4,这显然不行,我们继续改写

    function Aaa(){
       this.name = [1,2,3];
    }
    
    Aaa.prototype.showName = function(){
        alert(this.name);
    }
    
    
    function Bbb(){
        Aaa.call(this);
    }
    
    Bbb.prototype.constructor = Bbb;
    
    var F = function(){};
    F.prototype = Aaa.prototype;
    Bbb.prototype = new F();
    var b1 = new Bbb();
    
    b1.name.push(4);
    
    var b2 = new Bbb();
    console.log(b2.name);     //[1,2,3]

    这样就完美了

  • 相关阅读:
    从 java 代码到 android 进程的详细过程
    c++ 智能指针
    linux 进程间共享内存示例
    visual studio 在windows远程调试 linux 程序 cout 输出乱码
    wcf restful 访问报错 *.svc HTTP error 404.17
    c++ 创建 uuid guid
    c++ 事件回调 java
    java通过jna调用so
    java执行jar包
    java调用com组件com4j
  • 原文地址:https://www.cnblogs.com/chenzhiyu/p/8820224.html
Copyright © 2011-2022 走看看