Home >Web Front-end >JS Tutorial >Object-oriented Javascript core supports code sharing_javascript skills

Object-oriented Javascript core supports code sharing_javascript skills

WBOY
WBOYOriginal
2016-05-16 17:53:24872browse

The JQury framework is definitely the first choice for page development. The code is short and powerful. The disadvantage is that it lacks object-oriented features. Fortunately, there are many plug-ins! As for Ext, it is a behemoth. It is highly object-oriented and similar to MFC's huge API and control library. When it runs, Browsers are very tired, and development is very difficult. Using code to create interfaces is definitely a bad way. The weak language type of Javascript makes Ext development like walking in a minefield. The only way to reduce bugs is not to write bugs. Once they appear, Bug, debugging will be an extremely painful thing! Tracing and jumping through thousands of lines of code is really frustrating!

When Javascript does object-oriented development, it always uses many methods to simulate object-oriented features. These methods constitute the core code that supports object-oriented Javascript. The following is part of the code, which references a lot of JQuery With the core code of Ext, it is not bad for learning, and you can also do some small development!

Copy code The code is as follows:

/*
Function: Core script method
Author: LQB
2008-12-22
*/
var JCore = {//Construct core object
version:1.0,
$import:function(importFile){
var file = importFile.toString();
var IsRelativePath = (file.indexOf("$")==0 ||file.indexOf ("/")==-1);//Relative path (relative to JCore)
var path=file;
if(IsRelativePath){//Calculate path
if(file.indexOf(" $")==0)
file = file.substr(1);
path = JCore.$dir file;
}
var newElement=null,i=0;
var ext = path.substr(path.lastIndexOf(".") 1);
if(ext.toLowerCase()=="js"){
var scriptTags = document.getElementsByTagName("script");
for(var i=0;ilength;i ) {
if(scriptTags[i].src && scriptTags[i].src.indexOf(path)!=-1)
return;
}
newElement=document.createElement("script");
newElement.type="text/javascript";
newElement.src=path;
}
else if(ext.toLowerCase ()=="css"){
var linkTags = document.getElementsByTagName("link");
for(var i=0;ilength;i ) {
if(linkTags[i].href && linkTags[i].href.indexOf(path)!=-1)
return;
}
newElement=document.createElement("link");
newElement.type="text/ css";
newElement.rel="Stylesheet";
newElement.href=path;
}
else
return;
var head=document.getElementsByTagName("head") [0];
head.appendChild(newElement);
},
$dir : function(){
var scriptTags = document.getElementsByTagName("script");
for(var i=0;ilength;i ) {
if(scriptTags[i].src && scriptTags[i].src.match(/JCore/.js$/)) {
path = scriptTags[i]. src.replace(/JCore/.js$/,"");
return path;
}
}
return "";
}(),
$ : function (element){
return (typeof(element) == 'object' ? element : document.getElementById(element));
},
browser : {
isFirefox:navigator.userAgent.toLowerCase ().indexOf ('gecko') != -1,
isChrome:navigator.userAgent.toLowerCase().indexOf ('chrome') != -1,
isOpera:navigator.userAgent.toLowerCase() .indexOf ('opera') != -1,
isIE:navigator.userAgent.toLowerCase().indexOf ('msie') != -1,
isIE7:navigator.userAgent.toLowerCase().indexOf ('7.0') != -1
},
onReady: function(newFunction){
if(typeof(newFunction) == 'undefined')
return false;
this. domReady = false;
if(typeof(functions) == 'undefined')
var functions = [];
functions.push(newFunction);

var initial = function() {//Execution event list
for(var i=0; i< functions.length;i ){
functions[i]();
}
}
this.ready = function(){//Loading event
if(this.domReady)
initial();
var Browser = JCore.browser;
if (Browser.isFirefox || Browser.isOpera || Browser .isChrome) {//FX
try {
document.removeEventListener('DOMContentLoaded', initial);
}catch(e){}
document.addEventListener('DOMContentLoaded', initial, false );
this.domReady = true;
}
else if (Browser.isIE) {//IE
var timer = window.setInterval(function(){
try {
var IsReady = false;
document.body.doScroll("left");
IsReady=true;
initial();
window.clearInterval(timer);
this.domReady = true;
}
catch (e){
if(IsReady){//The document loading has been completed, and the exception thrown indicates that there is an error in the method called
var ErrorMsg = "In the method of onReady An error occurred!/r/n";
ErrorMsg ="Error message:" e.message "/r/n";
ErrorMsg ="Error description:" e.description "/r/n";
ErrorMsg ="Error type:" e.name "/r/n";
alert(ErrorMsg);
window.clearInterval(timer);
}
}
}
, 5);
}
}
this.ready();
},
apply:function(oDes, oSrc,bReplace){//Copy the attributes of other objects for the object, bReplace optional
if(oDes && oSrc && typeof(oSrc) == 'object'){
for(var p in oSrc){
if(bReplace == false && oDes[p] != null ) { continue; }
oDes[p] = oSrc[p];
}
}
return oDes;
},
override : function(origclass, overrides){/ /Add overloaded methods to the class, eg: override(function class(){},{A:function(){},B:function(){}});
if(overrides){
var p = origclass.prototype;
for(var method in overrides){
p[method] = overrides[method];
}
}
},
extend :function( ){
// inline overrides
var inlineOverride = function(o){
for (var m in o) {
this[m] = o[m];
}
};
/*The base class method that needs to be overloaded needs to be defined in the parent class prototype;
* The visibility of the method in the subclass: attributes in the subclass construction > attributes in the parent class construction >Attributes defined by the subclass prototype==overrides>Attributes defined by the parent class prototype
* Since the overrides method is attached to the prototype of the subclass, so: the attributes defined by the subclass prototype and overrides are defined after the two It can be seen that the
* extend method will override the prototype of the subclass, so defining attributes on the prototype of the subclass must be defined after the extend() method is called to be valid
* For a class: attributes defined in the constructor >Attributes defined by prototype
*
* Guidelines for class derivation:
* 1. It is recommended to define overridable methods in the base class in the base class prototype
* 2. If you are deriving The attribute method defined in the prototype of the class must be after the extend() method
* 3. Call the construction of the base class in the construction of the derived class:
* if (Sub.superclass) //sub is the subclass Name
* Sub.superclass.constructor.call(this, Args);//Args is the parameters of the constructor method of the parent class
* 4. Pay attention to the shallow copy problem of the array
*Example:
* var ClassA=function(){this.Show=function(){alert("Hello World!");}};
* var ClassB=function(){};
* JCore.extend(ClassB ,ClassA);
* var ObjectB = new ClassB();
* ObjectB.Show();
*/
return function(subFn, superFn, overrides){//Subclass, parent Class, overloaded method (optional)
var F = function(){}, subFnPrototype, superFnPrototype = superFn.prototype;
F.prototype = superFnPrototype;
subFnPrototype = subFn.prototype = new F( ;
}
subFn.override = function(obj){//override
JCore.override(subFn, obj);
};
subFnPrototype.override = inlineOverride;
if( overrides)
JCore.override(subFn, overrides);
return subFn;
};
}(),//Brackets are essential, indicating that the method returned internally is called
namespace: function (ns){//eg: JCore.namespace("JCore", "JCore.util");
var args=arguments, o=null, i, j, d, rt;
for (i= 0; ilength; i) {//Traversal parameters
d=args[i].split(".");//Traversal point separator
rt = d[0];
eval(' if (typeof ' rt ' == "undefined"){' rt ' = {};} o = ' rt ';');
for (j=1; jlength; j) {
o[d [j]]=o[d[j]] || {};
o=o[d[j]];
}
}
},
isEmpty : function( value){
return value === null || typeof(value) === 'undefined' || value === '';
},
idSeed : 0,
id : function(el, prefix){
prefix = prefix || "JCore-gen";
el = this.$(el);
var id = prefix (this.idSeed );
return el ? (el.id ? el.id : (el.id = id)) : id;
}
};
/*-------------- ----------------------------------Function object extension----------------- --------------------------*/
var FunctionExtendMethod ={
createCallback : function(/*args...*/ ){//This parameter is the creator’s parameter
/*Example: function func1(arg1,arg2){alert(arg1 arg2);}
* var myfunc = func1.createCallback(1,2);
* myfunc();//That is, func1 is called
**/
var args = arguments;
var method = this;
return function(/*args...*/) {//If parameters are passed when calling, the parameters passed when creating are invalid
var callArgs = arguments.length>0 ? arguments : args;
return method.apply(window, callArgs);
};
},
createDelegate: function(argsArray,scope){//The parameter is optional
//The parameter is an array, which is different from createCallback: the createCallback parameter is a variable parameter, and the argsArray parameter of createDelegate must be Array
var method = this;
return function(/*args...*/) {//If parameters are passed when calling, the parameters passed when creating are invalid
var callArgs = typeof( argsArray)=="undefined"?[]:argsArray;
callArgs = arguments.length>0 ? arguments : callArgs;
return method.apply(scope||window, callArgs);
};
},
defer: function(millis/*,args...*/){//Parameters: delay time (milliseconds), optional parameter list
/*Example: function func1(arg1,arg2){alert (arg1 arg2);}
* func1.defer(1000,1,2);//Func1(1,2) was called with a delay of 1 second
**/
var callArgs = Array.prototype. slice.call(arguments, 1);
var fn = this.createDelegate(callArgs);
if(millis){
return setTimeout(fn, millis);
}
fn( );
return 0;
},
createInterceptor : function(fcn, scope){
if(typeof fcn != "function"){
return this;
}
var method = this;
return function() {
fcn.target = this;
fcn.method = method;
if(fcn.apply(scope || this || window, arguments) === false){
return;
}
return method.apply(this || window, arguments);
};
}
};
JCore.apply(Function.prototype,FunctionExtendMethod);
/*---------------------------------- ----------String object extension------------------------------------- ---*/
var StringExtendMethod ={
trim : function(){//Remove leading and trailing spaces
return this.replace(/(^/s*)|(/s*$)/g ,"");//Replace the spaces before and after the string with empty strings.
},
replaceAll : function (AFindText,ARepText){//Replace all, replace only replaces the first one
raRegExp = new RegExp(AFindText,"g");
return this.replace (raRegExp,ARepText);
},
htmlEncode: function(){//Encode HTML and decode Html. Filter out double quotes, single quotes, symbols &, symbols <, symbols
return this.replace(/&/g,"&").replace(/<").replace(/>/g, ">").replace(//"/g,""").replace(//'/g,"'");
},
htmlDecode: function(){
return this.replace(//&/;/g, '/&').replace(//>/;/g, '/>').replace(//},
format : function (){
var args=arguments;
return this.replace(//{(/d )/}/g, function(m, i){
return args[i];
});
},
convertWarpSymbol : function(){
var reg1,reg2,reg3;
if(this.toLowerCase().indexOf("")!=-1){
reg1 = / /gi; reg2 = //gi;
return this.replace(reg1," ").replace(reg2,"/r/n");
}
else{
reg1 = / /g;reg2 = //r/n/gi;
return this.replace(reg1," ").replace(reg2,"
");
}
},
IsNum : function(){
var reg = /^/d $/g;
return reg.test(this);
}
};
JCore. apply(String.prototype,StringExtendMethod);
JCore.apply(String,{//Static method
trim : function(str){//Remove leading and trailing spaces
return str.replace(/(^/ s*)|(/s*$)/g,"");//Replace the spaces before and after the string with empty strings.
}
});
/*---------------------------------- ----------Array object extension----------------------------------------- --*/
var ArrayExtendMethod ={//Remove duplicate elements in the array
strip : function(){
if(this.length<2) return [this[0]]||[] ;
var arr=[];
for(var i=0;ivar repeat=false;
for(var j=0;jlength;j ){
if(this[i]===arr[j])
repeat=true;
}
if(!repeat)
arr.push(this[i]) ;
}
return arr;
},
exists : function(item){
for( var i = 0 ; i < this.length ; i ){
if ( item === this[i])
return true;
}
return false;
},
indexOf : function(item){
for (var i = 0 ; i < this.length; i ){
if(this[i] === item) return i;
}
return -1;
},
remove : function (item){
var index = this.indexOf(item);
if(index != -1){
this.splice(index, 1);
}
return this ;
}
};
JCore.apply(Array.prototype,ArrayExtendMethod);
/*--------------------- -----------------------Date object extension------------------------ ----------------*/
var DateExtendMethod ={//Return time interval (milliseconds)
getElapsed : function(date) {
return Math.abs ((date || new Date()).getTime()-this.getTime());
}
};
JCore.apply(Date.prototype,DateExtendMethod);
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn