收藏一个JavaScript字符串连接方法

最近在看一同事写的代码时,有一个字符串用了一堆"+"号,看了半天没明天到底会输出什么样的内容,就想到用字符串连接的类,把以前的方法写成了类的方式,方便调用。下面的类支持实例调用和静态调用,参数可以是单独的字符串,或者json的格式,或者类似参数数组的方式,见下面示例:

/**
* @class String concat
* @return {StrBuf/String}
* @constructor
* eg:
	var buf = new StrBuf("contructor str
");
	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 method
	console.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 invoke
			buf = new StrBuf();
			return buf.push.apply(buf, args).toString();
		}
	}
};
StrBuf.prototype = {
	// add String to the instance
	push: 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("");
	}
};

调用示例如下:

	var buf = new StrBuf("contructor str
");
	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"));
原文地址:https://www.cnblogs.com/xiaoyang002/p/4049928.html