js设计模式小结

1 构造函数模式

var Person = function(name){
this.name = name;
this.getName = function(){
console.log(this.name);
}
};

var Person1= new Person('xiaoming');
Person1.getName();
var Person2 = new Person('xiaohua');
Person2.getName();

使用构造函数模式可以实现重复创建多个相似对象,且可以实现自定义传参,但缺点是每次实例化一个对象时就相当于将该对象方法重新创建了一遍。

 2 原型模式

var Person = function(){
};
Person.prototype.name = 'xiaoming';
Person.prototype.getName = function() {
console.log(this.name);
};

var Person1 = new Person();
Person1.getName();
var Person2 = new Person();
Person2.getName();

原型模式的优点在于,每次实例化一个对象时,不需要重新创建该对象方法,而是通过指针引用原型链的方法,缺点是不能自定义传参,所以就有了下面的构造函数和原型组合使用的模式
 3 构造函数+原型模式

var Person = function(name){
this.name = name;
};

Person.prototype.getName = function() {
console.log(this.name);
};

var Person1 = new Person('xiaoming');
Person1.getName();
var Person2 = new Person('xiaohua');
Person2.getName();

综合了构造函数和原型模式的双方优点
4 工厂模式

function createPerson(name){
var Person = new Object();
Person.name = name;
Person.getName = function(){
console.log(this.name);
} 
return Person;
}

var Person1= createPerson('xiaoming');
Person1.getName();
var Person2= createPerson('xiaohua');
Person2.getName();

工厂模式也可以用于创建多个相似对象,与构造函数函数模式相似,主要区别是在内部通过new Object()创建对象最后return 出来,但是存在无法判断对象类型的问题

5 模块模式

var person = function(name){

function getName(name){
console.log(name);
}

return {
getName: getName
}
}();

person.getName('xiaoming');

特别是在单页应用中常用的模式,可以理解为引入了私有变量特权方法的单例。

原文地址:https://www.cnblogs.com/houxiaohang/p/7463956.html