美文网首页
原型,原型链,继承

原型,原型链,继承

作者: 山猪打不过家猪 | 来源:发表于2020-01-22 23:27 被阅读0次

    原型定义

    prototype

    原型是function对象的一个属性,它定义了构造函数制造出的对象的公共祖先。通过该构造函数产的对象,可以继承原型的属性和方法。原型也是对象。

    Person.prototype.LastName = "123";   //祖先
    function Person(){
        
    }
    
    var person = new Person();
    var person1 = new Person();
    
    console.log(person.LastName)
    console.log(person1.LastName)
    >>>
    123
    123
    

    更改父类属性

    Person.prototype.LastName = "123";
    function Person(){
        this.LastName = '32131';
    }
    
    var person = new Person();
    var person1 = new Person();
    
    console.log(person.LastName)
    console.log(person1.LastName)
    >>>
    32131
    32131
    

    继承

    1.原型链继承

    Grand.prototype.lastName = 'Ji'
    function Grand(){
    
    
    }
    
    var grand = new Grand();
    
    function Father(){
        this.name = 'hehe';
    }
    
    var father = new Father();
    
    Son.prototype = father;
    
    function Son(){
    
    }
    var son = new Son();
    

    过多的继承了没用的属性。
    2.借用构造函数继承

    function Person(name,age,sex){
        this.name = name;
        this.age = age;
        this.sex = sex;
    }
    
    function Student(name,age,sex,grade){
        Person.call(this,name,age,sex);
        this.grade = grade;
    }
    
    var student = new Student();
    

    不能继承借用构造函数的原型;
    每次构造函数都要多走一个函数;
    3.共享原型

    Father.prototype.lastName = 'Deng';
    function Father(){
        
    }
    
    function Son(){
    
    }
    Son.prototype = Father.prototype;
    
    var son = new Son();
    

    改写封装成一个函数

    Father.prototype.lastName = 'Deng';
    function Father(){
        
    }
    
    
    function Son(){
    
    }
     
    function inherit(Target,Origin){ 
        Target.prototype = Origin.prototype
        
    }
    
    inherit(Son,Father)
    var son = new Son();
    var father = new Father();
    

    会影响父类属性

    4.圣杯模式

    function inherit(Target,Origin){ 
        function F(){};
        F.prototype=Origin.prototype;
        Target.prototype = new F();
        Target.prototype.constructor = Target; //继承的所属
        Target.prototype.uber= Origin.prototype;
    }
    Father.prototype.lastName = 'Deng';
    function Father(){
        
    }
    
    function Son(){
    
    }
     
    
    inherit(Son,Father)
    var son = new Son();
    var father = new Father();
    

    相关文章

      网友评论

          本文标题:原型,原型链,继承

          本文链接:https://www.haomeiwen.com/subject/kxivzctx.html