My JavaScript prototype extension Functions

Source: Internet
Author: User
Document directory
  • String. Prototype. Format
  • Date. Prototype. Format
  • Function. Prototype. Delegate
  • Bunker!

You must declare in advance that I do not agree with the method of intruding JavaScript Object prototypes. However, the reason for this is the frequency of use. If these methods are not frequently called, they will never be immediately added to the prototype.

String. Prototype. format defines a string with a tag and replaces the tag with an input character. Each tag must be unique and grow itself like {0}, {1}... {n. For example:
VaR CLS = 'my-class', text = 'some text'; var S = string. format ('<Div class = "{0}" >{1} </div>', CLS, text); // s is now a string: s now contains the string: '<Div class = "My-class"> some text </div>'

String. Prototype. Format source code ):

/*** Format the string. * @ Param {string} string a string with a flag or a variable-length string parameter. * @ Param {string} the first value of value1, replace {0 }. The value to replace token {0} * @ Param {string} value2 second value, replace {1}... and so on (you can have any number ). Etc... * @ return {string} converted string. The formatted string */string. prototype. format = function () {var Regexp =/{(\ D +)}/g, replace = string. prototype. replace; function replaceel (M, I) {return this [I]; // This is arguments}/* at first run, with override it. */var fn = string. prototype. format = function () {replaceel. scope = arguments; // delegate scope return replace. call (this, Regexp, replaceel. delegate ();} return fn. apply (this, arguments); // first run}
Date. Prototype. Format

Format the date. See my previous blog article: javascript custom date Formatting Function http://blog.csdn.net/zhangxin09/archive/2011/01/01/6111294.aspx example:

alert(new Date().format("yyyy-MM-dd hh:mm:ss"));

Date. Prototype. Format source code is as follows:

/*** Format the date ** @ Param {string} format * @ return {string} */date. prototype. format = function (Format) {var $1, O = {"m +": This. getmonth () + 1, // month, starting from 0, "d +": This. getdate (), // Date "H +": This. gethours (), // Hour "m +": This. getminutes (), // minute "s +": This. getseconds (), // second // quarter "q +": math. floor (this. getmonth () + 3)/3), "S": This. getmilliseconds () // thousands of seconds}; var key, value; If (/(Y + )/. test ( Mat) {$1 = Regexp. $1, format = format. replace ($1, string (this. getfullyear ()). substr (4-$1);} For (key in O) {// if this parameter is not specified, the substring will continue to the end of stringvar. If (New Regexp ("(" + key + ")"). test (Format) {$1 = Regexp. $1, value = string (O [Key]), value = $1. length = 1? Value: ("00" + value). substr (value. length), format = format. Replace ($1, value) ;}} return format ;}
Function. Prototype. Delegate

Delegate () indicates the delegate, and function. Prototype. Delegate () indicates the delegate of the function. The delegate method word is widely used in the library I use. It can be used in two places, namely, in the function parameters and in the function scope. The latter refers to the encapsulated object (this or wrap closure ). The delegate method can change the this pointer of the function. Preset function scope. Measure the test taker's knowledge about the following two methods:

Function.prototype.delegateScope = function (scope){var self = this;return function(){return self.apply(scope, arguments);}}Function.prototype.delegateArgs = function(){var self  = this, args = arguments;    return function(){return self.apply(this, args);};}

Function. Prototype. Delegate source code ):

/*** Delegate the force ARGs function! So there's no ARGs, IT Server as ARGs! * @ Return {function} */function. prototype. delegate = function () {var self = This, scope = This. scope, argS = arguments, alength = arguments. length, fntoken = 'function'; return function () {var blength = arguments. length, length = (alength> blength )? Alength: blength; // mission one: For (VAR I = 0; I <length; I ++) {If (arguments [I]) {ARGs [I] = arguments [I]; // copy parameter} args. length = length; // under the MS JScript, there is still a problem with arguments as a number, that is, length cannot be automatically updated. For example, left: // mission two: For (VAR I = 0, j = args. length; I <j; I ++) {VaR _ Arg = ARGs [I]; If (_ Arg & typeof _ Arg = fntoken & _ Arg. late = true) {ARGs [I] = _ Arg. apply (scope | this, argS) ;}} return self. apply (scope | this, argS) ;};} if (! Function. prototype. BIND) {function. prototype. bind = function (scope) {This. scope = scope; return this. delegate () ;}}/*** sets a post function. * @ Param {function} composefn * @ Param {Boolean} isforcecall whether to forcibly execute the call method. Setting true is useful when arrays are used as separate objects. * @ Return {function} */function. prototype. after = function (composefn, isforcecall, scope) {var self = This; return function () {var result = self. apply (scope | this, arguments); If (isforcecall) {return composefn. call (this, result);} return result & (typeof result. pop! = 'Undefined') & (typeof result. Pop! = 'Unknown ')? Composefn. Apply (this, result): composefn. Call (this, result );};}
Bunker!

I once used string. Prototype. Format and found that it depends on function. Prototype. delegate, and it is very tiring to say that it is a closure and a regular expression. So I tried to search for a better solution on the Internet. I didn't want to find a very concise idea at first! Very natural and efficient. Looking back at the previous work, it may have started from this simple process, but the more you get, the more you get lost. Now it's really "anti-human ".

String.prototype.format = function () {var str = this; for(var i = 0, j = arguments.length; i < j; i++){str = str.replace(new RegExp('\\{' + i +'\\}', 'g'), arguments[i]);}return str;}console.log('hihih {0}, ,{2}'.format('dfasda', '34324343','dffds34324'));

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.