Javascript使用克隆的原型模式

  • ECMAScript 5中提供了Object.create()方法。
  • 使用这个方法很容易克隆一个一模一样的对象。
var animal=function(){
      this.blood=100;
      this.attackLevel=1;
      this.defenseLevel=1;
};
var a=new animal();
a.blood=1000;
a.attackLevel=15;
a.defenseLevel=9;

//调用克隆方法
var cloneAnimal=Object.create(a);
console.log(cloneAnimal);//输出:Object{blood:1000,attackLevel:15,defenseLevel:9}
  • 当然有些比较旧的浏览器不支持ES5,可用下面代码替换:
Object.create=Object.create||function(obj){
      var F=function(){};
      F.prototype=obj;
      return new F();  
}
原文地址:https://www.cnblogs.com/meiyh/p/6424478.html