zoukankan      html  css  js  c++  java
  • 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
    
  • 相关阅读:
    java 内存命令
    sts4 集成 springboot 和 activiti5
    sts4 安装spring xml 的提示。
    去除office 2019 由于您的登录凭据已经过期,的提示。
    「なきゃ」和「なくちゃ」分别是什么的原型?
    能力考必看|推荐三本适合N1和N2能力考练听力的书|帝京日语
    影子练习
    早大前辈分享日本留学生考试(EJU)日语高分经验
    星野源 新垣结衣 结婚
    使Nginx支持更多并发 请求的 Linux内核参数的优化
  • 原文地址:https://www.cnblogs.com/ouzilin/p/5164302.html
Copyright © 2011-2022 走看看