一些面向对象语言中支持多继承,在JavaScript也能实现多继承,可是有一些局限,由于在JavaScript中继承是依赖原型prototype链实现的,只有一条原型链,因此理论上是不能继承多个父类的。可是JavaScript很灵活,经过一些技巧方法能够继承多个对象的属性来实现相似的多继承。javascript
继承单对象的extend方法:css
//单继承 属性复制 var extend = function (target,source) { //遍历源对象中的属性 for(var property in source){ //将源对象中的属性复制到目标对象中 target[property] = source[property]; } //返回目标对象 return target; };
单继承的测试代码html
//测试代码 var book ={ name:'javascript', alike:['css','html5','js'] } var anotherBook = { color :'blue' } extend(anotherBook,book); console.log(anotherBook.name);//javascript console.log(anotherBook.alike);//[ 'css', 'html5', 'js' ] anotherBook.alike.push('ajax'); anotherBook.name = '设计模式'; console.log(anotherBook.name);//设计模式 console.log(anotherBook.alike);//[ 'css', 'html5', 'js', 'ajax' ] console.log(book.name);//javascript console.log(book.alike);//[ 'css', 'html5', 'js', 'ajax' ]
上面的方法能够实现对一个对象属性的复制继承,当传递多个对象时,便可实现多继承。html5
//多继承 属性复制 var mix = function () { var i =1,//从第二个参数起为被继承的对象 len =arguments.length,//获取参数长度 target = arguments[0], //第一个对象为目标对象 arg;//缓存参数对象 for(;i<len;i++){ //缓存当前对象 arg = arguments[i]; //遍历被继承对象中的属性 for(var property in arg){ //将被继承对象的属性复制到目标对象中 target[property] = arg[property]; } } //返回目标对象 return target; };
mix方法的做用是将传入的多个对象的属性复制到源对象中,这样便可实现对多个对象的属性的继承。另外当使用的时候须要传入目标对象(第一个参数-须要继承的对象)时,能够将它绑定到原生对象Object上,这样全部的对象均可以拥有这个方法。这样就能够在对象上直接调用。java
Object.property.mix = function () { var i=0,//从第一个参数起为被继承的对象 len =arguments.length,//获取参数长度 arg;//缓存参数对象 for(;i<len;i++){ //缓存当前对象 arg = arguments[i]; //遍历被继承对象中的属性 for(var property in arg){ this[property] = arg[property]; } } }