几种常见的继承

原文地址:http://blog.csdn.net/caoyafeicyf/article/details/53354112  

嘎嘎

常见的继承有扩展原型对象实现继承、替换原型对象实现继承、混入继承、混入+原型继承、经典继承、借用构造函数实现继承这六种。每个人的叫法可能不同,但是原理都一样。

扩展原型对象实现继承

实现原理:函数有一个prototype的属性(原型对象),通过给这个原型对象添加一个属性、方法,从而可以让构造函数的实例可以访问到

function Person(){}
Person.prototype.name="Jim";
Person.prototype.sayHello=function () {
    console.log("Hello");  
}

var p1=new Person();
console.log(p1.name) //输出"Jim"
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

替换原型对象实现继承

上面这种方式是最简单的也是最好理解的,但是有缺点,设置少数的属性或者方法还可以,但是要是设置多个呢?这种继承方法就不行了,太麻烦了,于是有了这种继承方式:替换原型对象实现继承。用于多个属性、方法的实现。

function Person () {}
Person.prototype={
   constructor:Person,
   a1:function () {},
   a2:function () {},
   a3:function () {},
   a4:function () {},
   a5:function () {},
   .......
}
var p1=new Person();
p1.a1();
p1.a2();
.......
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

注意:使用这种方式继承,必须要加上constructor:Person:Person这个属性,因为Person.prototype会将原型对象的这个属性替换掉,如果不加上,值将不指向构造函数。

混入继承

使用场景:已知对象o1,o3,需要将o1中的属性、方法拷贝到o3里面。

var o1={name:"张三",age:18,height:180};
var o2=function () {};
o2.prototype.a="a";
var o3=new o2();
//功能封装
function mixin(target,source) {
   for(var key in source) {
      target[key]=source[key];
   }
   return target;
}

mixin(o3,o1)//这样o3里面就有了o1的属性和方法了。
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

注意:jQuery里面的extend方法就是这个原理实现的。

混入+原型继承

利用混入继承向原型对象中添加属性和方法,其本质还是用了混入继承封装的方法

function Person () {};
Person.prototype.extend=function (source) {
   mixin(Person.prototype,source);
}

Person.prototype.extend({a:20,b:25,c:30});
//其实就相当于Person.prototype.a=20;Person.prototype.b=25......

var p1=new Person();
//p1就可以直接访问p1.a;p1.b了。
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

注意:在jQ中,如果你想要在jQ上面添加方法,用的是$.fn.extend(),其实它就相当于jquery.prototype.extend()

经典继承

由道格拉斯提出。使用场景:已知一个对象o,需要创建一个新的对象,这个新的对象继承自对象o。

//功能封装
function create(o) {
    function F(){}
    F.prototype=o;
    return new F(); 
}

var o={name:"张三",age:18};
var o2=create(o);//这样o2就继承自o了
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

借用构造函数实现继承

使用场景:子类构造函数借用父类构造函数来完成,给子类的实例添加属性。

function f1(name,age){
   this.name=name;
   this.age=age;
}

function f2(name,age,length) {
    f1.call(this,name,age)
    this.length=length;
}

var ff2=new f2("张三",23,180);
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

总结:这几种方法原理虽然不难,但是难的是如何灵活运用,这个也没办法,只能自己实践。

 
1
原文地址:https://www.cnblogs.com/gs97/p/7472919.html