extjs底层源码实现继承分析

先说明一下在js中一般的继承是怎么写的

var farther=function(name){
		this.name=name
	};
	farther.prototype={
		constructor:farther,   //还原构造器
		id:10
	};
	var child=function(sex,age){
		this.sex=sex;
		this.age=age;
	}
	child.prototype=new farther('tom');  //实现原型继承。
	var mychild=new child('男',23);
	alert(mychild.name); //tom
	alert(mychild.sex);	//男
	alert(mychild.age);//23
	alert(mychild.id);//10

 这种js中不符合我们的习惯,我们想要实现实例化的时候,写成这样  var mychild=new child('tom','男',23);

要实现上面这种模式,js有一种在子类引用父类的一种方法,这样父类十分庞大的时候。效率是很低的。下面来看一下ext是怎么实现的。

function myextend(sub , sup){
	        var F = function() {},		//定义一个空函数做为中转函数
	            subclassProto,			//子类的原型对象
	            superclassProto = sup.prototype;	//把父类的原型对象 交给了superclassProto变量
	        F.prototype = superclassProto;	// 做中转的位置:把父类的原型对象 赋值给了 F这个空函数的原型对象
	        subclassProto = sub.prototype = new F();	//进行原型继承
	        subclassProto.constructor = sub;		//还原构造器
	        sub.superclass = superclassProto;		//做了一个保存,保存了父类的原型对象
			//目的是为了防止你大意了
	        if (superclassProto.constructor === Object.prototype.constructor) {
	            superclassProto.constructor = sup;
	        }	
	};
	myextend(child,farther);
	var mychild=new child('tom','男','25');
	alert(mychild.name);//tom
	alert(mychild.sex);//男
	alert(mychild.age);//25

 ext巧妙的用了中转函数来实现。

来正式用ext实现继承

Ext.define('father',{
		config:{
			name:'f1',
			age:34
		},
		say:function(){
			alert('father is saying')
		},
		//给当前定义的类加一个构造器,构造器的用途是接受参数,初始化信息.
		constructor:function(config){  
			var me=this;
			me.initConfig(config);
		}
	});
	Ext.define('child',{
		extend:'father',
		config:{
			sex:'男'
		},
		constructor:function(config){  
			var me=this;
			me.initConfig(config);
		}
	});
	var mychild=Ext.create('child',{
		
	});
	alert(mychild.getName()); //f1
	alert(mychild.getAge());  //34
	mychild.say();     //father is saying

 

posted @ 2016-01-27 19:08  俗家弟子  阅读(893)  评论(0编辑  收藏  举报