javascript设计模式 - 组合模式

守給你的承諾、 提交于 2019-11-26 23:11:28

1:构造函数 + 原型模式

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

CreateFn.prototype.run = function(){
  return "这是原型上的一个 共享方法";
}

var fn1 = new CreateFn("lume",18);
var fn2 = new CreateFn("lume",18);
fn2.arr.push("添加一个")
console.log(fn1.arr);
console.log(fn2.arr);

console.log(fn1.name);
console.log(fn2.name);

console.log(fn1.run());
console.log(fn2.run());

console.log(fn1.run === fn2.run);

这里写图片描述
把需要共享的 添加到 该函数的 原型(prototype)上:
这就实现了 , 该共享的共享 ,该私有的 私有 !

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!