Js 中如何创建一个和 Date 一样可以直接输出为字符串的函数

我们知道,一旦实例化或者静态调用 Date,就可以直接将其输出为一条包含简略时间信息的字符串,即使它是一个对象或函数。
例如这样:

var now = new Date();
console.log(now); //会输出类似 un Mar 12 2017 12:59:15...
console.log(Date()); //结果相同
那么问题来了,自己要如何创建一个用户函数,能够实现类似的功能呢?

 function obj2string(o){ 
    var r=[]; 
    if(typeof o=="string"){ 
        return "\""+o.replace(/([\'\"\\])/g,"\\$1").replace(/(\n)/g,"\\n").replace(/(\r)/g,"\\r").replace(/(\t)/g,"\\t")+"\""; 
    } 
    if(typeof o=="object"){ 
        if(!o.sort){ 
            for(var i in o){ 
                r.push(i+":"+obj2string(o[i])); 
            } 
            if(!!document.all&&!/^\n?function\s*toString\(\)\s*\{\n?\s*\[native code\]\n?\s*\}\n?\s*$/.test(o.toString)){ 
                r.push("toString:"+o.toString.toString()); 
            } 
            r="{"+r.join()+"}"; 
        }else{ 
            for(var i=0;i<o.length;i++){ 
                r.push(obj2string(o[i])) 
            } 
            r="["+r.join()+"]"; 
        }  
        return r; 
    }  
    return o.toString(); 
} 

输出对象时默认调用对象的toString方法,重写Date对象的toString方法返回你需要的字符串

     Date.prototype.toString = function () {
        var s = '';
        s = this.getFullYear() + '-' + (this.getMonth() + 1) + '-' + this.getDate() + ' ' + this.getHours() + ':' + this.getMinutes() + ':' + this.getSeconds();
        return s;
    }
    var now = new Date();
    alert(now);