Created
October 6, 2014 03:21
-
-
Save hacke2/30f63fc392704fb8c95e to your computer and use it in GitHub Desktop.
克隆
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//浅克隆 | |
/*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