Recently, when I was reading the code written by a colleague, there was a string with a bunch of + numbers. After reading the code for half a day, what would be output tomorrow?
Recently, when I was reading the code written by a colleague, there was a string with a bunch of "+" numbers. After reading the code for half a day, what content will be output tomorrow, just think of a class connected with a string, and write the previous method into the class method for convenient calling. The following classes support instance calls and static calls. parameters can be separate strings, json format, or similar to parameter arrays. See the following example:
/*** @class String concat* @return {StrBuf/String}* @constructor* eg:var buf = new StrBuf("contructor str\n");buf.push("hello,").push("Today is {0}, {1}", "Monday", "March 28th").push("${name} is a good ${category} company", {name: "Google", category: "Intenet"});document.write(buf);// auto call toString methodconsole.log(buf);console.log(StrBuf("static {0} method", "invoke"));*/var StrBuf = function(s) {this.data = [];if(s) {var args = arguments, buf;if(this instanceof StrBuf) {this.push.apply(this, args);}else {// static invokebuf = new StrBuf();return buf.push.apply(buf, args).toString();}}};StrBuf.prototype = {// add String to the instancepush: function(s, j) {var args = arguments;if(args.length < 2) {this.data.push(s || "");}else if(typeof j == 'object') {this.data.push(s.replace(/\$\{([\w.]+)\}/g, function($, $1) {return ($1 in j) ? j[$1] : $;}));}else {this.data.push(s.replace(/\{(\d+)\}/g, function($, $1) {return args[+$1 + 1];}));}return this;},toString: function() {return this.data.join("");}};
Call example:
var buf = new StrBuf("contructor str\n");buf.push("hello,"); buf.push("Today is {0}, {1}", "Monday", "March 28th"); buf.push("${name} is a good ${category} company", {name: "Google", category: "Intenet"}); document.write(buf);// auto call toString method console.log(buf); console.log(StrBuf("static {0} method", "invoke"));
This article is available at http://www.nowamagic.net/librarys/veda/detail/1167.