javascript设计模式 - 动态原型模式

动态原型模式
其实就是在 函数里 加个判断 , 为了解决 多次实例化后 ,原型只初始化一次 !

function CreateFn(name,age) {
  this.name = name;
  this.age = age;
  this.arr = [1,2,3];

  if(typeof this.run != "function"){
    console.log("ok");
    CreateFn.prototype.run = function(){
      return "这是原型上的一个 共享方法";
    }
  }

}



var fn1 = new CreateFn("lume",18);
var fn2 = new CreateFn("lume",18);

不管实例化 多少次 , console.log(“ok”); 也只输出一次 !

你可能感兴趣的:(JavaScript,JavaScript,设计模式)