美文网首页JavaScript基础教程
JS(十五)继承模式,命名空间,对象枚举(上)

JS(十五)继承模式,命名空间,对象枚举(上)

作者: StevenTang | 来源:发表于2018-03-17 11:54 被阅读15次

    写在最前面

    继承的发展史

    • 传统形式 --> 原型链
      • 过多的继承了没有用的属性
    • 借用构造函数
      • 不能继承借用构造函数的原型
      • 每次构造函数都要多走一个函数
    • 共享原型
      • 不能随便改动自己的原型
    • 圣杯模式
    原型链的继承
    
    
    A.prototype.name = "wu";
    function A (){
        
    }
    var a = new A();
    
    B.prototype = a;
    function B (){
        
    }
    var b = new B();
    
    
    C.prototype = b;
    function C (){
        
    }
    
    var c = new C();
    
    借用构造函数继承
    
    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 sutdent = new Student();
    

    共享原型
    Father.prototype.lastName = "tang"
    function Father(){
        
    }
    
    function Son() {
        
    }
    
    Son.prototype = Father.prototype;
    
    var son = new Son();
    var father =  new Father();
    
    //缺点不能随便修改自己的原型
    
    比如我在下面
    Son.prototype.sex = "male";
    son.sex//打印出"male";
    father.sex = "male";
    因为他们两个的原型指向了同一个地方;
    
    圣杯模式
    Father.prototype.lastName = "tang"
    function Father(){
        
    }
    
    //我自己设置个中间层
    function F(){
        
    }
    
    function Son() {
        
    }
    
    F.prototype = Father.prototype;
    
    Son.prototype = new F();
    
    //设置成一个中间层
    //这样子写的好处就是son在自己的原型上面加东西
    // 不会影响别的原型,因为son的原型是new F(); new F的原型才是Father.prototype
    
    function inherit (Target,Origin){
        function F(){}
        F.protptype = Origin.protptype;
        Targrt.prototype = new F();
        Targrt.prototype.constructor = Target;
        Targrt.prototype.uber = Origin.prototype
        
    }
    
    Father.prototype.lastName = "wu";
    function Father(){
        
    }
    
    function Son(){
        
    };
    
    

    相关文章

      网友评论

        本文标题:JS(十五)继承模式,命名空间,对象枚举(上)

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