- 工厂模式:在一个函数中创建一个对象,并赋予这个对象属性和方法
例如:function factory(name, job) { var o = new Object(); o.name = name; o.job = job; o.sayName = function () { console.log(this.name); }; return o; } var factory1 = factory("suning", "worker");
- 构造函数模式:创建实例,通过this指定属性和方法,没有返回值,再通过new调用
例如:function Person(name, age, job) { this.name = name; this.age = age; this.job = job; this.sayName = function () { console.log(this.name); }; } var person1 = new Person("Lucy", 22, "worker");
- 原型模式:主要是先创建一个原型对象,再使用prototype原型链来继承
例如:function Person() { } Person.prototype.name = "Lucy"; Person.prototype.age = 30; Person.prototype.job = "worker"; Person.prototype.sayName = function () { console.log(this.name); }; var person1 = new Person();
- 组合模式:使用构造函数定义属性,使用原型模式定义方法和共享的属性,构造函数和原型分开
例如:function Person(name, age, job) { this.name = name; this.age = age; this.job = job; } Person.prototype = { constructor: Person, sayName: fucntion () { console.log(this.name); } } var person1 = new Person("Lucy", 30, "worker");
- 动态原型链模式:检查某个方法是否有效,来初始化原型,原型在构造函数的内部
例如:function Person(name, age, job) { this.name = name; this.age = age; this.job = job; if(typeof this.sayName != "function") { Person.prototype.sayName = function () { console.log(this.name); }; } } var friend = new Person("Lucy", 30, "worker");
- 寄生构造函数模式:在使用工厂模式创建的构造函数中创建对象,并使用new初始化
例如:function Person(name, age, job) { var o = new Object(); o.name = name; o.age = age; o.job = job; o.sayName = function () { console.log(this.name); }; return o; } var friend = new Person("Lucy", 40, "worker");
- 稳妥构造函数模式:不使用this和new的构造函数
例如:function Person(name, age, job) { var o = new Object(); o.sayName = function () { console.log(name); }; return o; } var friend = Person("Lucy", 30, "worker");
掌握原型链对于理解JS的设计模式至关重要: