JavaScript创建对象

 1 // 工厂模式
 2 function createPerson(name, age){
 3     var o = new Object();
 4     o.name = name;
 5     o.age = age;
 6     o.show = function(){
 7         alert("hello s");
 8     };
 9     return o;
10 }
11 var person = createPerson("zhangsan", "22");
12 person.show(); 
hello s


 1 // 构造函数模式
 2 function Person(name,age){
 3     this.name = name;
 4     this.age = age;
 5     this.show = function(){
 6         alert("hello");
 7     }
 8 }
 9 var person = new Person("zhangsan", "20");
10 person.show();
hello


1 // 原型模式
2 function Person(){
3 }
4 Person.prototype.name = "kuikui";
5 var person = new Person();
6 alert(person.name);
kuikui


 1 // 组合构造原型
 2 function Person(name,age){
 3     this.name = name;
 4     this.age = age;
 5     this.show = function(){
 6         alert("hello");
 7     }
 8 }
 9 Person.prototype = {
10     constructor :Person,
11     name : "kuikui",
12     say : function(){
13         alert("say me");
14     }
15 }
16 var person1 = new Person("aa","23");
17 person1.say();
18 alert(person1.name);//构造优先原型 aa
say me
aa


 1 // 动态原型
 2 function Person(name, age){
 3     this.name = age;
 4     this.age = age;
 5     if(typeof this.show != "function"){
 6         this.show = function(){
 7             alert("构造 show");
 8         }
 9     }
10     this.test = function(){
11         alert("构造 test");
12     }
13 }
14 Person.prototype = {
15     show : function(){
16         alert("原型 show")
17     }
18 }
19 var person = new Person();
20 var person1 = new Person();
21 person.show();
22 person1.test();
23 //alert(Person.prototype.show); 
原型 show
构造 test


原文地址:https://www.cnblogs.com/kkcodin/p/5412029.html