3、面向对象---多继承

在javascript中继承时依赖于原型prototype链实现的,只有一个原型链,理论上是不能继承多个父类的。javascript是灵活的,通过一些技巧方法却可以继承多个对象的属性来实现类似的多继承。

1 var extend = function(target,source){
2     //遍历原对象中属性
3     for(var property in source){
4         //将原对象中的属性复制到目标对象中
5         target[property] = source[property];
6     }
7     //返回目标对象
8     return target;
9 }

extend 方法的实现就是对对象中的属性的一个复制过程,extend 方法是一个浅复制过程,jquery中也实现该方法:

 1 var  book = {
 2     name : 'jsbook',
 3     all : ['test1','test2']
 4 }
 5 var other = {
 6     say : 'hello'
 7 }
 8 
 9 extend(other,book);
10 console.log(other.name); //jsbook
11 console.log(other.all);  // ['test1','test2']
12 
13 other.name = 'htmlbook';
14 other.all.push('test3');
15 console.log(other.name); //htmlbook
16 console.log(other.all); //['test1','test2','test3']

这只是单继承,要实现多继承往下看。。。

可以将它绑定到原生对象object上,这有所有的对象就可以拥有这个方法了

 1 Object.prototype.mix = function(){
 2     var i =0,  //从第一个参数起为被继承对象
 3         len = arguments.length, //获取参数长度
 4         arg;  //缓存参数对象
 5         //遍历被继承对象
 6         for(; i<len;i++){
 7             //缓存当前对象
 8             arg = arguments[i];
 9             //遍历被继承对象中的属性
10             for(var prototype in arg){
11                 //将被继承对象中的属性复制到目标对象中
12                 this[prototype] = arg[prototype];
13             }
14         }
15 
16 }

这样就可以在对象上直接调用了。如:

1 other.mix(boo1,boo2);
2 console.log(other); //返回 继承book2\book2图书信息

 

posted on 2016-08-31 07:27  Mc525  阅读(153)  评论(0)    收藏  举报

导航