[js] clone
#函数复制
Function.prototype.clone = function() { var s = this.toString(); var front = s.replace(/^[^\(]*\(/, ''); var middle = front.replace(/\)[^\)]*\{[\s\S]+\}$/, ''); var after = front.replace(/^[^\{]*\{|\}$/g, ''); if (middle) { return new Function(middle, after); } return new Function(after); };
#
Function.prototype.clone = function() { return new Function('return ' + this.toString())(); };
# Number、String、Object、Array、Boolean 值复制
function clone(Obj) { var buf; //指针 if (Obj instanceof Array) { buf = []; //创建一个空的数组 var i = Obj.length; while (i--) { buf[i] = clone(Obj[i]);//防止属性是数组或对象 } return buf; } else if (Obj instanceof Object) { buf = {}; //创建一个空对象 for (var k in Obj) { //为这个对象添加新的属性 buf[k] = clone(Obj[k]); } return buf; } else { //普通变量直接赋值 return Obj; } } console.log(clone(['xx','yy','zz'])); console.log(clone({'a':'xx','b':'yy','c':'zz'})); console.log(clone(233));