最近在学习prototype.js代码,想利用其中的继承来学习一下javascript中的oo思想。碰见到了一些问题,如下
/* * 第一种方法,不使用prototype的继承 * 这是以前在学习继承时使用的继承方法, */ function d(ui){ if(!ui){ return; } this.param1 = document.createElement(ui); } function e(ui){ if(!ui){ return; } this.base = d; this.base(ui); this.param2 = document.createElement(ui); } e.prototype = new d(); function f(ui){ if(!ui){ } this.base = e; this.base(ui); } f.prototype = new e(); var e1 = new e("div"); var e2= new e("div"); var f1 = new f("div"); var f2 = new f("div"); //能够拿到不同的param1对象 alert(e1.param1 ==e2.param1); //返回false alert(f1.param2 == f2.param2);//返回false /* * 第二种方法,使用prototype继承 */ var a = Class.create(); a.prototype = { initialize:function(ui ){ this.param1 = document.createElement(ui); } } var b = Class.create(); b.prototype = Object.extend(new a(),{ initialize:function(ui){ this.param2 = document.createElement(ui); } }) var c = Class.create(); c.prototype = Object.extend(new b(),{ initialize:function(param){ } }) var b1 = new b("div"); var b2= new b("div"); var c1 = new c("div"); var c2 = new c("div"); //这里本意是每一个对象都能拿到自己的一个param1的属性 //但是这里拿到的是同一个引用 alert(b1.param1 == b2.param1);//return true alert(c1.param2 == c2.param2);//return true
我的问题是我想用prototype的方法实现第一种代码的实现,在继承后,子类能拿到自己的在父类中param1对象,但是却发生了第二种代码的情况,这应该是由prototype中继承机制导致的,prototype中继承代码如下:
Object.extend = function(destination, source) { for (var property in source) { destination[property] = source[property]; } return destination; } //继承实现时如: b.prototype = Object.extend(new a(),{}}
我参照ajax.base中形式改进了第二种方法如下:
/* *第三种方法 */ var a = Class.create(); a.prototype = { initialize:function(param){ this.init(param); }, init:function(param){ this.param1 = document.createElement(ui); } } var b = Class.create(); b.prototype = Object.extend(new a(),{ initialize:function(param){ this.init(param); this.param2 = document.createElement(ui); } }) var c = Class.create(); c.prototype = Object.extend(new b(),{ initialize:function(param){ //this.init(param); } }) var b1 = new b("div"); var b2= new b("div"); var c1 = new c("div"); var c2 = new c("div"); alert(b1.param1 == b2.param1);//return false alert(c1.param2 == c2.param2);//return true
第三种方法我用一个init方法在每个对象中给param1赋值,这样每个子类能拿到不同的param1对象,但是这样多重继承后设置子类的属性时非常的不方便,请问有什么改进的方法吗?
原文地址:http://www.javaeye.com/topic/192877
还有其他的不错的文章 收藏:http://www.javaeye.com/wiki/topic/143473