Object-oriented JavaScript core support code sharing _JAVASCRIPT skills

Source: Internet
Author: User
Tags extend shallow copy time interval
Jqury Framework is definitely the first choice for the development of the page, the code is short and strong, the disadvantage is the lack of object-oriented features, fortunately there are many plug-ins! As for ext is a giant, highly object-oriented, similar to MFC's huge API and Control library, run up, the browser is very tired, development is also very hard, Using code to create an interface is definitely a bad way, JavaScript's weak language type makes ext development like walking in the minefield, the only way to reduce bugs is not to write bugs, once a bug, debugging will be a very painful thing! In thousands of lines of code tracking, jump really makes people crazy!

JavaScript to do object-oriented development, always use a lot of simulation of object-oriented methods, these methods constitute the support of object-oriented JavaScript core code, the following is part of the code, which refers to a lot of jquery and ext core code, used to learn well, can also do some small development!
Copy Code code as follows:

/*
Features: Core scripting methods
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) {//calculation 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 () {//Execute Event List
for (var i=0; i< functions.length;i++) {
Functions[i] ();
}
}
This.ready = function () {//Load 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) {//Document loading is complete, throw an exception to indicate that the method that was invoked is wrong
var errormsg = "Onready error occurred in the 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) {//copies the properties 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) {//To 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 implement overloading needs to be defined in the parent class prototype;
* Visibility of methods in subclasses: properties in Subclass constructs > Properties > Subclasses in prototype-defined attributes ==overrides> Parent-class prototype defined properties
* Since the overrides method is appended to the prototype of the subclass, the subclass prototype the defined properties and overrides, both of which are defined as visible
* The Extend method overrides the prototype of the subclass, so defining the property on the prototype of the subclass must be defined after the Extend () method call is valid
* For a class: the property defined in the construct >prototype the attribute defined
*
* Criteria derived from the class:
* 1. It is recommended to define an overridable method in the base class in the base class prototype
* 2. If you define a property method in the prototype of a derived class, you must follow 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 method of the parent class
* 4. Note the problem of shallow 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, overloaded 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;
};
} (),//bracket is not small, represents the method of calling internal return
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 calls the FUNC1
**/
var args = arguments;
var method = this;
return function (/*args...*/) {//If parameters are passed at call time, the newsletters parameter is created is invalid
var Callargs = arguments.length>0? Arguments:args;
Return method.apply (window, Callargs);
};
},
Createdelegate:function (Argsarray,scope) {//parameter optional
An array of arguments, distinguished from createcallback: The createcallback parameter is a variable parameter, and the createdelegate Argsarray parameter must be an array
var method = this;
return function (/*args...*/) {//If parameters are passed at call time, the newsletters parameter is created 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: Delay time (ms), optional parameter list
/* Example: function func1 (ARG1,ARG2) {alert (ARG1+ARG2);}
* Func1.defer (1000,1,2)//delay 1 seconds call func1 (1,2)
**/
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 trailing spaces
Return This.replace (/(^/s*) | ( /s*$)/g, ""), or a space before and after the string, replaced with an empty string.
},
Replaceall:function (Afindtext,areptext) {//Replace all, replace replaces only the first
Raregexp = new RegExp (Afindtext, "G");
Return This.replace (Raregexp,areptext);
},
Htmlencode:function () {//encoding HTML and decoding HTML. Filter out double quotes, single quotes, symbols, symbols
Return This.replace (/&/g, "&"). Replace (/<). Replace (/>/g, ">"). Replace (//"/g," ""). Replace (//'/g, "'");
},
Htmldecode:function () {
Return This.replace (//&/;/g, '/& '). Replace (//>/;/g, '/> '). Replace (//</;/g, '/< '). Replace (// ;/g, '/'). Replace (//&/#39/;/g, '/');
},
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 trailing spaces
Return Str.replace (/(^/s*) | ( /s*$)/g, ""), or a space before and after the string, replaced with an empty string.
}
});
/*--------------------------------------------Array Object extension----------------------------------------/*
var Arrayextendmethod ={//Remove the duplicated elements in the array
Strip:function () {
if (this.length<2) return [this[0]]| | [];
var arr=[];
for (Var i=0;i<this.length;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 time interval (ms)
Getelapsed:function (date) {
Return Math.Abs (date | | | new Date ()). GetTime ()-this.gettime ());
}
};
Jcore.apply (Date.prototype,dateextendmethod);
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.