zoukankan      html  css  js  c++  java
  • 继承第一节(call继承、拷贝继承、寄生组合继承)

    1、call 继承

    类式(call)继承(一般类式继承是继承属性)
    调用父类,通过call来改变this(把window改成子类)达到继承属性的目的。
    function Person(name,age){
            this.name = name;
            this.age = age;
        }
        function Coder(name,age,job){
            Person.call(this,name,age);//改变了this指向
            this.job = job;
            // console.log(this);//Coder
        }
        let p = new Person('a',18);
        let c = new Coder('ab',16,'猿妹');
    
        console.log(c);//这样就继承了Person下的一些属性,
    
    

    2、拷贝继承

    遍历父类原型上的方法,只要是自身的就赋值给子类的原型
     function Person(name,age){
            this.name = name;
            this.age = age;
        }
        Person.prototype.say = function(){
            console.log('我叫'+this.name);
        }
        Person.prototype.runing = function(){
            console.log('我会跑');
        }
    
        function Coder(name,age,job){
            Person.call(this,name,age);
            this.job = job;
        }
        // Coder.prototype = Person.prototype; //此时赋址了
    
        Object.prototype.aa = 20;
    
        for(let attr in Person.prototype){ //因为in会遍历原型,所以只有父类原型上的属性才会赋值
            if(Person.prototype.hasOwnProperty(attr)){
                Coder.prototype[attr] = Person.prototype[attr];
            }
        }
    
        Coder.prototype.runing = function(){
            console.log('会骑UFO');
        }
    
        let p = new Person('a',18);
        let c = new Coder('b',16,'前端');
    
        c.runing();
        p.runing();
    
        console.log(Coder.prototype);//

    3、

    Object.create:内置Object类天生自带的方法
    1.创建一个空对象
    2.让新创建的空对象的__proto__指向第一个传递进来的对象
     function Person(name,age){
            this.name = name;
            this.age = age;
        }
        Person.prototype.say = function(){
            alert('我的名字'+this.name);
        }
        Person.prototype.runing = function(){
            alert('我会跑');
        }
    
        function Coder(name,age,job){
            Person.call(this,name,age);
            this.job = job;
        }   
    
        Coder.prototype = Object.create(Person.prototype);
    
        // Coder.prototype = Object.assign({},Person.prototype); //类似拷贝
    
    
        //  Object.assign(Coder.prototype,Person.prototype)
    
    
      
        Coder.prototype.say = function(){
            alert('duang,duang,duang,123!~');
        }
    
        let c = new Coder('a',26,'超级码农');
        let p = new Person('b',26);
    
        c.say();
        p.say();
    代码的世界很精彩,好的代码需要慢慢的打磨。
  • 相关阅读:
    利用idea里面的mysql插件进行导入sql文件
    JSTL标签
    deepin20系统下配置JAVA开发环境
    deepin20安装及问题解决
    SpringBoot 在项目启之后执行自定义方法的两种方式
    Nick 的经验书
    Java 经验书
    SpringBoot 经验书
    Linux 经验书
    在MacOS中启动SSH服务
  • 原文地址:https://www.cnblogs.com/Allisson/p/9902065.html
Copyright © 2011-2022 走看看