Skip to content

Instantly share code, notes, and snippets.

@hacke2
Created October 6, 2014 03:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save hacke2/30f63fc392704fb8c95e to your computer and use it in GitHub Desktop.
Save hacke2/30f63fc392704fb8c95e to your computer and use it in GitHub Desktop.
克隆
//浅克隆
/*Object.prototype.clone = function (){
var obj = {};
for(var key in this) {
if(this.hasOwnProperty(key)) {
obj[key] = this[key];
}
}
return obj;
}*/
//浅克隆测试
/*var a = {
name : 'test'
};
var b = a.clone();*/
Object.prototype.clone = function (){
var obj = {};
for(var key in this) {
if(this.hasOwnProperty(key)) {
if(typeof this[key] == 'function' || typeof this[key] == 'object') {
obj[key] = this[key].clone();
}else {
obj[key] = this[key];
}
}
}
return obj;
}
Array.prototype.clone = function (){
var arr = [];
for (var i = this.length - 1; i >= 0; i--) {
if(typeof this[i] == 'function' || typeof this[i] == 'object') {
arr[i] = this[i].clone();
}else {
arr[i] = this[i];
}
};
return arr;
}
Function.prototype.clone = function (){
var that = this;
var newFunc = function (){
return that.apply(this, arguments);
}
for (var key in this) {
newFunc[key] = this[key];
};
return newFunc;
}
/*var obj = {
name : 'hehe',
like : ['man', 'woman'],
display : function() {
console.log(this.name);
}
};
var newObj = obj.clone();
newObj.like.push('other')
console.log(newObj);
console.log(obj);*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment