JS构造函数设计模式

来源:互联网 发布:笨方法学python在线 编辑:程序博客网 时间:2024/06/07 07:02

在上一篇文章中看到了工厂模式的缺点,又出现了构造函数的模式。工厂模式

function Person(name, age, sex) {    this.name = name;    this.age = age;    this.sex = sex;    this.sayInfo = function () {        console.log(this.name + "--" + this.age + "--" + this.sex);    };};function sayInfo() {    console.log(this.name + "--" + this.age + "--" + this.sex);}var person1 = new Person('z3', 20, 'boy');var person2 = new Person('l4', 21, 'girl');
console.log(person1.sayInfo == person2.sayInfo);
console.log(person1 instanceof Person);console.log(person1 instanceof Object);
构造函数模式可以让实例是哪一种具体的类型,但是有一个缺点就是person1的sayInfo与person2的sayInfo函数不一样,因为在js中函数也是对象,所以每次调用function都会产生新的函数地址(new Functoin(),所以会产生新的地址),这就浪费了内存,使得每一个实例都会产生一个新的函数,所以出现了下列的解决方案。
function Person(name,age,sex){    this.name=name;    this.age=age;    this.sex=sex;    this.sayInfo=sayInfo;};function sayInfo (){    console.log(this.name+"--"+this.age+"--"+this.sex);}var person1=new Person('z3',20,'boy');var person2=new Person('l4',21,'girl');
console.log(person1.sayInfo == person2.sayInfo);
console.log(person1 instanceof Person);console.log(person1 instanceof Object);
这两个对象的函数地址一样,但是使得oo思想中的封装特性没有了安全感,所以出现了原型设计模式

0 0
原创粉丝点击