js原型继承的两种方法对比介绍

  在实际的项目中,我们通常都是用构造函数来创建一个对象,再将一些常用的方法添加到其原型对象上。最后要么直接实例化该对象,要么将它作为父类,再申明一个对象,继承该父类。

  而在继承的时候有两种常用方式,今天我们就来稍作探讨

  

复制代码 代码如下:

  //父类

  function Person(name){

  this.name = name;

  };

  // 子类

  function Student(sex){

  Person.apply(this,arguments); //继承父类的构造函数

  this.sex=sex;

  };

  1,继承Prototype:

  

复制代码 代码如下:

  Student.prototype = Person.prototype; //执行完此句时,Student.prototype.constructor 指向的是Person,为什么了?因为Person.prototype.constructor指向Person,对象的赋值实质上是引用赋值,所以Student.prototype.constructor也指向Person

  Student.prototype.constructor = Student;  //  将Student.prototype.constructor 指回Person

  用Person的原型对象来覆盖Student的原型对象;前面说到对象的赋值实质上是引用赋值,所以如果Student.prototype上的任何修改都会体现到Person.prototype中,即子类会影响父类。

  看下面:

  

复制代码 代码如下:

  Student.prototype.add=function(){alert("add")};

  Person.prototype.add();//弹出add

  2,继承实例:

  

复制代码 代码如下:

  Student.prototype = new Person();  //如果此处不传递参数,可以不写();即直接写成 new Person;

  2 Student.prototype.constructor = Student;

  用Person的实例来覆盖Student的原型对象;创建了实例,比起前面那种,显示是浪费内存了,不过这同时也解决了上面那种方法的缺点,即此时Student.prototype上的任何修改不会体现到Person.prototype中,即子类不会影响父类。

  3,利用控对象来组合1和2的优点,去掉缺点

  

复制代码 代码如下:

  var  F = function(){};

  F.prototype = Person.prototype;

  Student.prototype  = new F();

  Student.prototype.constructor  = Student;

  F是个空对象,上面只有些原型方法,实例化时内存占用较少,同时也隔离开了子类对父类的影响。