When Javascript is used for object-oriented development, many methods that simulate object-oriented features are always used. These methods constitute the JQury framework, the core code supporting object-oriented Javascript, which is definitely the first choice for page development, the code is short and powerful, but the disadvantage is the lack of object-oriented features. Fortunately, there are many plug-ins! As for Ext, it is a huge object. It is highly object-oriented, similar to the huge API and control library of MFC. When it runs, the browser gets tired and the development is awkward, using code to create an interface is definitely a bad way. The weak language type of Javascript makes Ext development like walking in the minefield. The only way to reduce bugs is not to write bugs. Once a bug occurs, debugging will be a very painful task! It's crazy to track and jump in thousands of lines of code!
When Javascript is used for object-oriented development, many methods that simulate object-oriented features are used. These methods constitute the core code supporting object-oriented Javascript. The following is part of the code, I have referenced a lot of core code of JQuery and Ext for learning well. You can also do some small development!
The Code is as follows:
/*
Function: Core script method
Author: LQB
2008-12-22
*/
Var JCore = {// construct the 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) {// computing 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 () {// list of execution events
For (var I = 0; I <functions. length; I ++ ){
Functions [I] ();
}
}
This. ready = function () {// load the event
If (this. domReady)
Initial ();
Var Browser = JCore. browser;
If (Browser. isFirefox | Browser. isOpera | Browser. isChrome) {// FX
Try {
Document. removeEventListener ('domainloaded', initial );
} Catch (e ){}
Document. addEventListener ('domainloaded', 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 has been loaded. if an exception is thrown, it indicates that an error occurred while calling the method.
Error in var ErrorMsg = "onReady method! /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) {// this parameter is optional for copying attributes of other objects to an object.
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) {// adds an overload method for the class, such as: 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 methods to be implemented to be overloaded must be defined in the parent class prototype;
* Method visibility in subclass: Properties in subclass construction> properties in parent class construction> properties defined by prototype of subclass = overrides> properties defined by prototype of parent class
* Because the overrides method is appended to prototype of the subclass, the attributes defined by prototype and overrides are visible.
* The extend method will override the prototype of the subclass. Therefore, defining attributes on the prototype of the subclass must be defined after the extend () method is called.
* For a class: properties defined in the constructor> properties defined by prototype
*
* Class-derived principles:
* 1. We recommend that you define methods that can be rewritten in the base class prototype.
* 2. If the property method is defined in prototype of the derived class, it 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 name of the subclass.
* Sub. superclass. constructor. call (this, Args); // Args is the parameter of the constructor of the parent class.
* 4. Pay attention to the shortest copy 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, reload method (optional)
Var F = function () {}, subFnPrototype, superFnPrototype = superFn. prototype;
F. prototype = superFnPrototype;
SubFnPrototype = subFn. prototype = new F ();
SubFnPrototype. constructor = subFn;
SubFn. superclass = superFnPrototype; // parent class
If (superFnPrototype. constructor = Object. prototype. constructor ){
SuperFnPrototype. constructor = superFn;
}
SubFn. override = function (obj) {// override
JCore. override (subFn, obj );
};
SubFnPrototype. override = inlineOverride;
If (overrides)
JCore. override (subFn, overrides );
Return subFn;
};
} (), // The brackets are indispensable, indicating that the internal return method 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) {// traverses the Parameter
D = args [I]. split ("."); // traverse the dot 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 parameter of the Creator.
/* Example: function func1 (arg1, arg2) {alert (arg1 + arg2 );}
* Var myfunc = func1.createCallback (1, 2 );
* Myfunc (); // call func1
**/
Var args = arguments;
Var method = this;
Return function (/* args... */) {// If a parameter is passed during the call, the parameter passed during creation is invalid.
Var callArgs = arguments. length> 0? Arguments: args;
Return method. apply (window, callArgs );
};
},
CreateDelegate: function (argsArray, scope) {// optional parameter
// An array of parameters, which is different from createCallback: The createCallback parameter is a variable parameter, and the argsArray parameter of createDelegate must be an array
Var method = this;
Return function (/* args... */) {// If a parameter is passed during the call, the parameter passed during creation is invalid.
Var callArgs = typeof (argsArray) = "undefined "? []: ArgsArray;
CallArgs = arguments. length> 0? Arguments: callArgs;
Return method. apply (scope | window, callArgs );
};
},
Defer: function (millis/*, args... */) {// parameter: latency (millisecond), list of optional parameters
/* Example: function func1 (arg1, arg2) {alert (arg1 + arg2 );}
* Func1.defer (, 1, 2); // func1 (1, 2) is 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.tar get = 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 spaces at the beginning and end
Return this. replace (/(^/s *) | (/s * $)/g, ""); // replace the leading and trailing spaces with empty strings.
},
ReplaceAll: function (AFindText, ARepText) {// replace all, replace only the first one
RaRegExp = new RegExp (AFindText, "g ");
Return this. replace (raRegExp, ARepText );
},
HtmlEncode: function () {// encode HTML and decode Html. Double quotation marks, single quotation marks, symbols &, symbols <, symbols are filtered out.
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 spaces at the beginning and end
Return str. replace (/(^/s *) | (/s * $)/g, ""); // replace the leading and trailing spaces with empty strings.
}
});
/* -------------------------------------------- Array object extension ----------------------------------------*/
Var ArrayExtendMethod = {// remove repeated elements from the array
Strip: function (){
If (this. length <2) return [this [0] | [];
Var arr = [];
For (var I = 0; I Var 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 interval (MS)
GetElapsed: function (date ){
Return Math. abs (date | new Date (). getTime ()-this. getTime ());
}
};
JCore. apply (Date. prototype, DateExtendMethod );