标签:
/*1、工厂模式*/ function createPerson(name,age,job) { var o = new object(); o.name = name; o.age = age; o.job = job; o.setName = function(newName) { this.name = newName; }; return o; } var person1 = createPerson("zcj", 21, "Soft Engineer"); /* 问题:只能创建多个相似的对象,不能识别对象 */
/*2、构造函数模式*/ function Person(name,age,job) { this.name = name; this.age = age; this.job = job; this.setName = function(newName) { this.name = newName; } } var person1 = new Person("zcj", 21, "Soft Engineer"); /* 问题:每个方法都要在实例上重新创建一遍 */
/*3、原型模式*/ function Person() { } person.prototype.name = "zcj"; person.prototype.age = 21; person.prototype.job = "Soft Engineer"; person.prototype.sayName = function() { alert(this.name); }; var person1 = new Person(); var person2 = new Person(); alert(person1.sayName == person2.sayName); //true person1.name = "Greg"; alert(person1.name); //"Greg" alert(person2.name); //"zcj" delete person1.name; alert(person1.name); //"zcj" /* 问题:所有实例在默认情况下取得相同的属性值;对于引用类型的属性,为所有实例共享(这是不期望的) */
/*4、组合使用构造函数模式和原型模式*/ function Person(name,age,job) { this.name = name; this.age = age; this.job = job; friends = ["Shelby","Court"] } Person.prototype = { constructor:Person, sayName: function() { alert(this.name); } } var person1 = new Person("zcj",21,"Soft Engineer"); var person2 = new Person("Gerg",27,"Doctor"); person1.friends.push("Van"); alert(person1.friends); //"Shellby,Court,Van" alert(person2.friends); //"Shellby,Court" alert(person1.friends === person2.friends); //false alert(person1.sayName === person2.sayName); //true /* 说明:使用最广泛,认同度最高的创建自定义类型的方法 */
/*5、动态原型模式*/ function Person(name,age,job) { this.name = name; this.age = age; this.job = job; if(typeof this.sayName != "function") { Person.prototype.sayName = function() { alert(this.name); }; } } var friend = new Person("zcj", 21, "Soft Engineer"); friend.sayName(); /* 说明:将所有信息封装在构造函数中,通过检查某个应该存在的方法是否有效,决定是否需要初始化 */
/*6、寄生构造函数模式*/ function Person(name,age,job) { var o = new object(); o.name = name; o.age = age; o.job = job; o.setName = function(newName) { this.name = newName; }; return o; } var person1 = new Person("zcj", 21, "Soft Engineer"); person1.setName("Gerg"); alert(person1.name); //"Gerg" /* 说明:与工厂模式区别:1、实例化对象要使用new;2、改包装函数为构造函数(函数名第一个字母大写) */
标签:
原文地址:http://www.cnblogs.com/Merc47/p/4767058.html