这个地方错的哪里?
- JScript code
function eventManage(){ this.eventList={};}eventManage.prototype={ //创建一个constructor指向 constructor:eventManage, //保存事件 addEvent:function(ev,fn) {}, //触发事件 startEvent:function(ev) {}, //清除事件 removeEvent:function(ev,fn) {} }function Prototype(obj){ function F(){} //创建一个临时原型 F.prototype=obj; //继承传入对象的属性和方法 return new F; //返回一个构造函数}//创建超类型副本function inPrototype(obj1,obj2){ var pro=Prototype(obj1.prototype); //创建超类型的副本对象 pro.cunstructor=obj2; //给副本对象增加一个constructor属性 obj2.prototype=pro; //把对象副本赋值给子类型}function oDemo(name){ eventManage.call(this); this.name=name;}inPrototype(oDemo,eventManage);oDemo.prototype.say=function(say){}function oDemo2(ev){}var a=new oDemo('abc');a.addEvent('a',oDemo2); //这个地方报错,错在哪里?a.say('着火了');
不改变这个代码结构的情况下,
问题在哪?
怎么解决?
求指点,谢谢。。。。。
[解决办法]
典型的寄生组合试继承。
function inPrototype(obj1,obj2)
{
var pro=Prototype(obj1.prototype); //创建超类型的副本对象
pro.cunstructor=obj2; //给副本对象增加一个constructor属性
obj2.prototype=pro; //把对象副本赋值给子类型
}
这句你调用方式是:inPrototype(oDemo,eventManage);
那么obj2.prototype =pro 就是eventManage.prototype =pro; 看出问题了吧? obj1.prototype是oDemo的原型对象,你用eventManage的原型来等于oDemo的原型 这不成了父类继续子类?
修改:
function inPrototype(obj1,obj2)
{
var pro=Prototype(obj2.prototype); //创建超类型的副本对象
pro.cunstructor=obj1; //给副本对象增加一个constructor属性
obj1.prototype=pro; //把对象副本赋值给子类型
}