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();
    代码的世界很精彩,好的代码需要慢慢的打磨。
  • 相关阅读:
    string.Format组合跳转路径
    jquery 设置asp:dropdownlist 选中项
    asp:UpdatePanel中js失效问题已解决
    repeater 一个td多个div显示图片
    aps.net js获取服务器控件
    nfs—文件转换器
    Linux之文件权限
    关于Linux与Windows的在服务器的一些区别
    关于Linux目录结构的理解
    新的旅程
  • 原文地址:https://www.cnblogs.com/Allisson/p/9902065.html
Copyright © 2011-2022 走看看