当前位置:Gxlcms > JavaScript > 面向对象Javascript核心支持代码分享

面向对象Javascript核心支持代码分享

时间:2021-07-01 10:21:17 帮助过:8人阅读

JQury框架绝对是页面开发的首选,代码短小强悍,缺点就是面向对象特性不足,所幸有不少插件!至于Ext就是一个庞然大物了,高度面向对象,类似于MFC的庞大API和控件库,运行起来,浏览器就累得够呛,开发也够呛,使用代码来创建界面绝对是个糟糕的方式,Javascript的弱语言类型使得Ext开发就像行走在雷区,减少bug的唯一方法就是不要写出bug,一旦出现bug,调试将是一件极为痛苦的事情 !在几千行代码里跟踪、跳转真让人抓狂!

Javascript做面向对象开发的时候,总是会用到很多模拟面向对象特性的方法,这些方法就构成了支撑面向对象Javascript的核心代码,以下就是部分代码,其中参考了很多JQuery与Ext的核心代码,用来学习还不错,也可以做一些小的开发!
代码如下:
  1. <br>/* <br>功能:核心脚本方法 <br>作者:LQB <br>2008-12-22 <br>*/ <br>var JCore = {//构造核心对象 <br>version:1.0, <br>$import:function(importFile){ <br>var file = importFile.toString(); <br>var IsRelativePath = (file.indexOf("$")==0 ||file.indexOf("/")==-1);//相对路径(相对于JCore) <br>var path=file; <br>if(IsRelativePath){//计算路径 <br>if(file.indexOf("$")==0) <br>file = file.substr(1); <br>path = JCore.$dir+file; <br>} <br>var newElement=null,i=0; <br>var ext = path.substr(path.lastIndexOf(".")+1); <br>if(ext.toLowerCase()=="js"){ <br>var scriptTags = document.getElementsByTagName("script"); <br>for(var i=0;ilength;i++) { <br>if(scriptTags[i].src && scriptTags[i].src.indexOf(path)!=-1) <br>return; <br>} <br>newElement=document.createElement("script"); <br>newElement.type="text/javascript"; <br>newElement.src=path; <br>} <br>else if(ext.toLowerCase()=="css"){ <br>var linkTags = document.getElementsByTagName("link"); <br>for(var i=0;ilength;i++) { <br>if(linkTags[i].href && linkTags[i].href.indexOf(path)!=-1) <br>return; <br>} <br>newElement=document.createElement("link"); <br>newElement.type="text/css"; <br>newElement.rel="Stylesheet"; <br>newElement.href=path; <br>} <br>else <br>return; <br>var head=document.getElementsByTagName("head")[0]; <br>head.appendChild(newElement); <br>}, <br>$dir : function(){ <br>var scriptTags = document.getElementsByTagName("script"); <br>for(var i=0;ilength;i++) { <br>if(scriptTags[i].src && scriptTags[i].src.match(/JCore/.js$/)) { <br>path = scriptTags[i].src.replace(/JCore/.js$/,""); <br>return path; <br>} <br>} <br>return ""; <br>}(), <br>$ : function(element){ <br>return (typeof(element) == 'object' ? element : document.getElementById(element)); <br>}, <br>browser : { <br>isFirefox:navigator.userAgent.toLowerCase().indexOf ('gecko') != -1, <br>isChrome:navigator.userAgent.toLowerCase().indexOf ('chrome') != -1, <br>isOpera:navigator.userAgent.toLowerCase().indexOf ('opera') != -1, <br>isIE:navigator.userAgent.toLowerCase().indexOf ('msie') != -1, <br>isIE7:navigator.userAgent.toLowerCase().indexOf ('7.0') != -1 <br>}, <br>onReady: function(newFunction){ <br>if(typeof(newFunction) == 'undefined') <br>return false; <br>this.domReady = false; <br>if(typeof(functions) == 'undefined') <br>var functions = []; <br>functions.push(newFunction); <br><br>var initial = function(){//执行事件列表 <br>for(var i=0; i< functions.length;i++){ <br>functions[i](); <br>} <br>} <br>this.ready = function(){//加载事件 <br>if(this.domReady) <br>initial(); <br>var Browser = JCore.browser; <br>if (Browser.isFirefox || Browser.isOpera || Browser.isChrome) {//FX <br>try { <br>document.removeEventListener('DOMContentLoaded', initial); <br>}catch(e){} <br>document.addEventListener('DOMContentLoaded', initial, false); <br>this.domReady = true; <br>} <br>else if (Browser.isIE) {//IE <br>var timer = window.setInterval(function(){ <br>try { <br>var IsReady = false; <br>document.body.doScroll("left"); <br>IsReady=true; <br>initial(); <br>window.clearInterval(timer); <br>this.domReady = true; <br>} <br>catch (e){ <br>if(IsReady){//文档加载已经完毕,抛出异常说明是调用的方法出错 <br>var ErrorMsg = "onReady的方法中发生错误!/r/n"; <br>ErrorMsg+="错误信息:"+e.message+"/r/n"; <br>ErrorMsg+="错误描述:"+e.description+"/r/n"; <br>ErrorMsg+="错误类型:"+e.name+"/r/n"; <br>alert(ErrorMsg); <br>window.clearInterval(timer); <br>} <br>} <br>} <br>, 5); <br>} <br>} <br>this.ready(); <br>}, <br>apply:function(oDes, oSrc,bReplace){//为对象拷贝其它对象的属性,bReplace可选 <br>if(oDes && oSrc && typeof(oSrc) == 'object'){ <br>for(var p in oSrc){ <br>if(bReplace == false && oDes[p] != null) { continue; } <br>oDes[p] = oSrc[p]; <br>} <br>} <br>return oDes; <br>}, <br>override : function(origclass, overrides){//为类增加重载方法,eg:override(function class(){},{A:function(){},B:function(){}}); <br>if(overrides){ <br>var p = origclass.prototype; <br>for(var method in overrides){ <br>p[method] = overrides[method]; <br>} <br>} <br>}, <br>extend :function(){ <br>// inline overrides <br>var inlineOverride = function(o){ <br>for (var m in o) { <br>this[m] = o[m]; <br>} <br>}; <br>/*需要实现重载的基类方法需要在父类prototype中定义; <br>* 在子类中方法的可见度:子类构造中的属性>父类构造中的属性>子类prototype定义的属性==overrides>父类prototype定义的属性 <br>* 由于overrides方法被附加到子类的prototype中,所以:子类prototype定义的属性与overrides,两者后定义的可见 <br>* extend方法将重写子类的prototype,因此在子类的prototype上定义属性则必须在extend()方法调用之后再定义才有效 <br>* 对于一个类:构造中定义的属性>prototype定义的属性 <br>* <br>*类派生的准则: <br>* 1.建议把基类中可重写的方法定义在基类prototype中 <br>* 2.如果在派生类的prototype中定义属性方法,必须在extend()方法之后 <br>* 3.在派生类的构造中调用基类的构造: <br>* if(Sub.superclass) //sub即子类的名称 <br>* Sub.superclass.constructor.call(this, Args);//Args即父类的构造方法的参数 <br>* 4.注意数组的浅拷贝问题 <br>*示例: <br>* var ClassA=function(){this.Show=function(){alert("Hello World!");}}; <br>* var ClassB=function(){}; <br>* JCore.extend(ClassB,ClassA); <br>* var ObjectB = new ClassB(); <br>* ObjectB.Show(); <br>*/ <br>return function(subFn, superFn, overrides){//子类,父类,重载方法(可选) <br>var F = function(){}, subFnPrototype, superFnPrototype = superFn.prototype; <br>F.prototype = superFnPrototype; <br>subFnPrototype = subFn.prototype = new F(); <br>subFnPrototype.constructor = subFn; <br>subFn.superclass = superFnPrototype;//父类 <br>if (superFnPrototype.constructor == Object.prototype.constructor) { <br>superFnPrototype.constructor = superFn; <br>} <br>subFn.override = function(obj){//override <br>JCore.override(subFn, obj); <br>}; <br>subFnPrototype.override = inlineOverride; <br>if(overrides) <br>JCore.override(subFn, overrides); <br>return subFn; <br>}; <br>}(),//括号不可少,表示调用内部返回的方法 <br>namespace : function(ns){//eg: JCore.namespace("JCore", "JCore.util"); <br>var args=arguments, o=null, i, j, d, rt; <br>for (i=0; ilength; ++i) {//遍历参数 <br>d=args[i].split(".");//遍历点分隔符 <br>rt = d[0]; <br>eval('if (typeof ' + rt + ' == "undefined"){' + rt + ' = {};} o = ' + rt + ';'); <br>for (j=1; jlength; ++j) { <br>o[d[j]]=o[d[j]] || {}; <br>o=o[d[j]]; <br>} <br>} <br>}, <br>isEmpty : function(value){ <br>return value === null || typeof(value) === 'undefined' || value === ''; <br>}, <br>idSeed : 0, <br>id : function(el, prefix){ <br>prefix = prefix || "JCore-gen"; <br>el = this.$(el); <br>var id = prefix + (this.idSeed++); <br>return el ? (el.id ? el.id : (el.id = id)) : id; <br>} <br>}; <br>/*--------------------------------------------Function对象扩展-------------------------------------------*/ <br>var FunctionExtendMethod ={ <br>createCallback : function(/*args...*/){//此参数即创造者的参数 <br>/*示例:function func1(arg1,arg2){alert(arg1+arg2);} <br>* var myfunc = func1.createCallback(1,2); <br>* myfunc();//即调用了func1 <br>**/ <br>var args = arguments; <br>var method = this; <br>return function(/*args...*/) {//如果在调用时传了参数,则创建时传的参数无效 <br>var callArgs = arguments.length>0 ? arguments : args; <br>return method.apply(window, callArgs); <br>}; <br>}, <br>createDelegate : function(argsArray,scope){//参数可选 <br>//参数一个数组,与createCallback区别:createCallback参数是可变参数,createDelegate的argsArray参数必须是数组 <br>var method = this; <br>return function(/*args...*/) {//如果在调用时传了参数,则创建时传的参数无效 <br>var callArgs = typeof(argsArray)=="undefined"?[]:argsArray; <br>callArgs = arguments.length>0 ? arguments : callArgs; <br>return method.apply(scope||window, callArgs); <br>}; <br>}, <br>defer : function(millis/*,args...*/){//参数:延迟时间(毫秒),可选参数列表 <br>/*示例:function func1(arg1,arg2){alert(arg1+arg2);} <br>* func1.defer(1000,1,2);//延迟1秒调用了func1(1,2) <br>**/ <br>var callArgs = Array.prototype.slice.call(arguments, 1); <br>var fn = this.createDelegate(callArgs); <br>if(millis){ <br>return setTimeout(fn, millis); <br>} <br>fn(); <br>return 0; <br>}, <br>createInterceptor : function(fcn, scope){ <br>if(typeof fcn != "function"){ <br>return this; <br>} <br>var method = this; <br>return function() { <br>fcn.target = this; <br>fcn.method = method; <br>if(fcn.apply(scope || this || window, arguments) === false){ <br>return; <br>} <br>return method.apply(this || window, arguments); <br>}; <br>} <br>}; <br>JCore.apply(Function.prototype,FunctionExtendMethod); <br>/*--------------------------------------------String对象扩展----------------------------------------*/ <br>var StringExtendMethod ={ <br>trim : function(){//去掉首尾空格 <br>return this.replace(/(^/s*)|(/s*$)/g,"");//将字符串前后空格,用空字符串替代。 <br>}, <br>replaceAll : function (AFindText,ARepText){//替换所有,replace只替换第一个 <br>raRegExp = new RegExp(AFindText,"g"); <br>return this.replace(raRegExp,ARepText); <br>}, <br>htmlEncode : function(){//编码HTML和解码Html。过滤掉双引号,单引号,符号&,符号<,符号 <br>return this.replace(/&/g,"&").replace(/<").replace(/>/g,">").replace(//"/g,""").replace(//'/g,"'"); <br>}, <br>htmlDecode : function(){ <br>return this.replace(//&/;/g, '/&').replace(//>/;/g, '/>').replace(//</;/g, '/<').replace(//"/;/g, '/'').replace(//&/#39/;/g, '/''); <br>}, <br>format : function(){ <br>var args=arguments; <br>return this.replace(//{(/d+)/}/g, function(m, i){ <br>return args[i]; <br>}); <br>}, <br>convertWarpSymbol : function(){ <br>var reg1,reg2,reg3; <br>if(this.toLowerCase().indexOf("")!=-1){ <br>reg1 = / /gi; reg2 = //gi; <br>return this.replace(reg1," ").replace(reg2,"/r/n"); <br>} <br>else{ <br>reg1 = / /g;reg2 = //r/n/gi; <br>return this.replace(reg1," ").replace(reg2," <br>"); <br>} <br>}, <br>IsNum : function(){ <br>var reg = /^/d+$/g; <br>return reg.test(this); <br>} <br>}; <br>JCore.apply(String.prototype,StringExtendMethod); <br>JCore.apply(String,{//静态方法 <br>trim : function(str){//去掉首尾空格 <br>return str.replace(/(^/s*)|(/s*$)/g,"");//将字符串前后空格,用空字符串替代。 <br>} <br>}); <br>/*--------------------------------------------Array对象扩展----------------------------------------*/ <br>var ArrayExtendMethod ={//去掉数组中重复的元素 <br>strip : function(){ <br>if(this.length<2) return [this[0]]||[]; <br>var arr=[]; <br>for(var i=0;i<this.length;i++){ <br>var repeat=false; <br>for(var j=0;jlength;j++){ <br>if(this[i]===arr[j]) <br>repeat=true; <br>} <br>if(!repeat) <br>arr.push(this[i]); <br>} <br>return arr; <br>}, <br>exists : function(item){ <br>for( var i = 0 ; i < this.length ; i++ ){ <br>if( item === this[i]) <br>return true; <br>} <br>return false; <br>}, <br>indexOf : function(item){ <br>for (var i = 0; i < this.length; i++){ <br>if(this[i] === item) return i; <br>} <br>return -1; <br>}, <br>remove : function(item){ <br>var index = this.indexOf(item); <br>if(index != -1){ <br>this.splice(index, 1); <br>} <br>return this; <br>} <br>}; <br>JCore.apply(Array.prototype,ArrayExtendMethod); <br>/*--------------------------------------------Date对象扩展----------------------------------------*/ <br>var DateExtendMethod ={//返回时间间隔(毫秒) <br>getElapsed : function(date) { <br>return Math.abs((date || new Date()).getTime()-this.getTime()); <br>} <br>}; <br>JCore.apply(Date.prototype,DateExtendMethod); <br>

人气教程排行