1、单对象克隆
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>singleClone</title>
<script type="text/javascript">
var clone = function(target,obj){
for(var index in obj){
target[index] = obj[index];
}
return target;
}
//测试用例
var book = {
name:'js设计模式',
type:'js'
}
var subBook = {
color:'blue'
}
clone(subBook,book);
console.debug(subBook.name);
console.debug(subBook.color);
//本例已经通过验证
</script>
</head>
<body>
</body>
</html>
2、多对象克隆
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>multipleClone</title>
<script type="text/javascript">
function Extend(){
var _f = function(){};
for(var i = 0; i < arguments.length; i++){
for(var index in arguments[i]){
_f.prototype[index] = arguments[i][index];
}
}
return new _f();
}
//测试用例
var penguin = Extend(
{
speed:20,
swim:function(){
console.log('游泳速度'+this.speed);
}
},
{
run:function(speed){
console.log('跑步速度'+speed);
}
},
{
jump:function(){
console.log('跳跃动作');
}
}
);
console.log(penguin.speed);
penguin.swim();
penguin.run(50);
penguin.jump();
//本例已经通过验证
</script>
</head>
<body>
</body>
</html>