继承总结(创造对象、原型链、组合继承、 寄生组合式继承)

 创造对象:

  工厂模式: 

    function createPerson(name,age){

                var  o=new Object();

              o.name=name;

            o.age=age;

                   o.sayName=function(){

                          console.log(this.name)

                   }

return   o;

}

var person1= createPerson('Owen',28);

构造函数模式:

fucntion Person(name,age){

    this.name=name;

    this.age=name;

    this.sayName=function(){ console.log(this.name)}

}

var person1=new Person('Owen',28);

原型模式:

 function Person(){}

   Person.prototype.name="owen";

   Person.prototype.age=28;

   Perspn.prototype.sayName=function(){console.log(this.name)}

原型链的基本概念:

一、首先理解构造函数、原型、实例的关系:

    1、 每一个构造函数都有一个原型对象,原型对象都包含一个指向构造函数的指针 :

                       如一个构造函数Person;    Person.prototype指向原型对象,Person.prototype.constructor指回了Person

    2、 而实例包含一个指向原型对象的内部指针:

                     实例 person1.[[Prototype]]指向Person.prototype ,这个[[Prototype]]是无法访问的,Person.prototype.isPrototypeOf(person1) ,返回true,谷歌可用person1.__proto__指向Person.prototype

 二、原型链的形成:

    如果让原型对象指向另一个类型的实例,那原型对象则会包含一个指向另一个原型的指针,相应的,另一个原型也函数指向另一个构造函数的指针,如果另一个原型又指向另一个类型的实例,如此层层递进,则构成实例与原型的链条

 组合继承:借用构造函数与原型链组合,但会两次调用父类 (这种继承模式使用最多)

 function SuperType(name){

       this.name=name;

      this.color=['red','yellow','blue']

  }

 SuperType.prototype.sayName=function(){

    console.log(this.name) 

}

function SubType(name,age){

   SuperType.call(this,name);  // 第二次调用SuperType()

    this.age=age;

}

SubType.prototype=new SuperType(); // 第一次调用SuperType()

SubType.prototype.constructor=SubType(); 

SubType.prototype.sayAge= function(){

   console.log(this.age);

}

寄生组合式继承:在组合继承上,优化(创建了一个副本,解决二次调用父类的问题)

 function inheritPrototype(subType,superType){

   var prototype = object(superType.prototype); //创建对象 ,其实 就只作了一个 父类的 副本,这样避免二次调用父类

    prototype.constructor=subType; //增强对象

   subType.prototype=prorotype; //指定对象

}

    function SuperType(name){

       this.name=name;

      this.color=['red','yellow','blue']

  }

 SuperType.prototype.sayName=function(){

    console.log(this.name) 

}

function SubType(name,age){

   SuperType.call(this,name);  // 调用SuperType() 一次

    this.age=age;

}

inheritPrototype(SubType,SuperType);

SubType.prototype.sayAge= function(){

   console.log(this.age);

}

猜你喜欢

转载自blog.csdn.net/wenmin1987/article/details/109967123