常见的四种原型继承

常见的四种原型继承

1、最原始的继承 子类原型继承父类的实例

	function Father() {
    
    
      this.firstName = '三'
    }
    var father = new Father();
    Father.prototype.lastName = '张';

    function Son() {
    
    
      this.firstName = '四';
      this.sex = '男';
    }
    // 子类原型继承父类的实例
    Son.prototype = father;
    var son = new Son()
    // son继承father
    console.log(son.lastName, son.firstName, son.sex);//张  四  男
    son.firstName = '五';
    console.log(son.firstName, father.firstName); //五  三
    Father.prototype.size = {
    
    
      face: '黄'
    }
    father.size.face = '白';
    console.log(son.size.face, father.size.face); //白 白

通过 Son.prototype = father实现继承,改变子级的属性父级不会改变。但如果父级的圆形链上属性发生改变,子级的也会改变。

2、原型的继承

	function Father() {
    
    }
    Father.prototype.lastName = 'shuai';
    Father.prototype.fn = function () {
    
    
      console.log('我是Father中函数输出的内容');
    }

    function Son() {
    
    }
    Son.prototype.sex = 'women';
    Son.prototype = Father.prototype;
    var son = new Son();

    Son.prototype.wife = 'girl';
    var father = new Father()

    console.log(son.wife, father.wife); //girl girl

原型的继承他们使用 同一个原型,会造成原型的污染

3、call方法继承(非标准继承)

	function Father(name,age,sex){
    
    
            // son中添加对应的属性
            // this -> Son中的this
            this.name = name;
            this.age = age;
            this.sex = sex;
    }
    Father.prototype.car = '4个圈';
    function Son(name,age,sex){
    
    
       Father.call(this,name,age);
       this.girlFriend = 'girl1';
    }
    var son = new Son('张三',38,);  
    console.log(son);

4、圣杯模式,定义一个新的构造函数,将新构造函数原型等于父级原型,子级原型等于新的构造函数的实例对象

		function Father(){
    
    }
        Father.prototype.lastName = 'OY';
        
        function Son(){
    
    }

        // 定义一个新的构造函数
        function Temp(){
    
    }
        Temp.prototype = Father.prototype;
        // new Temp()  出现一个新的{}   {}.__proto__  == Father.prototype
        Son.prototype = new Temp();

        var son = new Son();
        // son.__proto__ -> temp -> Father.prototype

        console.log(son.__proto__.constructor);// Father(){}  Son默认情况下

        // 记录son原本的构造函数
        Son.prototype.constructor = Son;
        // 记录son原本继承自谁 添加一个属性去记录
        Son.prototype.uber = Father.prototype;
        console.log(son.uber);

这种方法会让原始继承的原型会改变,所以加入到一个uber属性中。

猜你喜欢

转载自blog.csdn.net/yun_shuo/article/details/114597268
今日推荐