导读:
JavaScript由于对象使用原形继承,原形链只能有一条,所以一般不能实现多继承,就算是多继承,也是把别的构造函数内容拿过来,修改一下context在原来构造函数基础上继续执行,我写了个自认为可以实现多继承的函数
代码
Object.extend = function(destination, source) { for (var property in source) destination[property] = source[property]; return destination;}; Object.prototype.mix=function(sub){ sub.call(this); var temp=Object.extend({},sub.prototype); temp.__proto__=this.__proto__; this.__proto__=temp}
使用:
代码
>>>function test(){this.a=123} >>> test.prototype.b=345 345 >>> a={} Object >>> a.mix(test) >>> a Object a=123 b=345 >>> function test2(){this.c=678} >>> test2.prototype.test3=789 789 >>> a.mix(test2) >>> a Object a=123 c=678 test3=789 b=345
其中定义了空对象a,后分别继承自test和test2构造函数,都有prototype继承,并且对于原构造函数无侵入影响
代码
>>>test2.prototype Object test3=789 >>> test.prototype Object b=345
主要是利用closure封闭住__proto__原原形上级,中间使用temp中转,各位高手看看这样可行吗,我想不出来不使用__proto__实现的方法
本文转自
http://hzjavaeyer.group.javaeye.com/group/blog/132590
JavaScript由于对象使用原形继承,原形链只能有一条,所以一般不能实现多继承,就算是多继承,也是把别的构造函数内容拿过来,修改一下context在原来构造函数基础上继续执行,我写了个自认为可以实现多继承的函数
代码
Object.extend = function(destination, source) { for (var property in source) destination[property] = source[property]; return destination;}; Object.prototype.mix=function(sub){ sub.call(this); var temp=Object.extend({},sub.prototype); temp.__proto__=this.__proto__; this.__proto__=temp}
使用:
代码
>>>function test(){this.a=123} >>> test.prototype.b=345 345 >>> a={} Object >>> a.mix(test) >>> a Object a=123 b=345 >>> function test2(){this.c=678} >>> test2.prototype.test3=789 789 >>> a.mix(test2) >>> a Object a=123 c=678 test3=789 b=345
其中定义了空对象a,后分别继承自test和test2构造函数,都有prototype继承,并且对于原构造函数无侵入影响
代码
>>>test2.prototype Object test3=789 >>> test.prototype Object b=345
主要是利用closure封闭住__proto__原原形上级,中间使用temp中转,各位高手看看这样可行吗,我想不出来不使用__proto__实现的方法
本文转自
http://hzjavaeyer.group.javaeye.com/group/blog/132590