【读书笔记】对象创建摘录

 1 //工厂模式
 2 function createPerson(name, age, job){
 3     var o = new Object();
 4     o.name = name;
 5     o.age = age;
 6     o.job = job;
 7     o.sayName = function(){
 8         alert(this.name);
 9     }
10     return o;
11 }
12 function createPerson(name, age, job){
13     return {
14         name:name,
15         age:age,
16         job:job,
17         sayName:function(){
18             alert(this.name);
19         }
20     }
21 }
22 
23 //构造函数模式
24 function Person(name, age, job){
25     this.name = name;
26     this.age = age;
27     this.job = job;
28     this.sayName = function(){
29         alert(this.name);
30     }
31     //每个对象的sayName都是不同的函数  解决办法:sayName用一个全局函数赋值
32 }
33 
34 //String.startsWith
35 String.prototype.startsWith = function(text){
36     return this.indexOf(text) == 0;
37 }
38 
39 //原型模式
40 function Person(){}
41 Person.prototype = {
42     constructor:Person,
43     name:"default",
44     age:0,
45     job:"coder",
46     friends:["jim","jack"],//所有实例共享这个属性,修改一个对所有实例生效,如果其他实例没有覆盖这个属性的话
47     sayName:function(){
48         alert(this.name);
49     }
50 }
51 
52 //组合使用构造函数模式和原型模式
53 function Person(name, age, job){
54     this.name = name;
55     this.age = age;
56     this.job = job;
57     this.friends = ["Shelby", "Court"];
58 }
59 Person.prototype = {
60     constructor:Person,
61     sayName:function(){
62         alert(this.name);
63     }
64 }
65 
66 //动态原型模式
67 function Person(name, age, job){
68     this.name = name;
69     this.age = age;
70     this.job = job;
71     if(typeof this.sayName != "function"){
72         Person.prototype.sayName = function(){
73             alert(this.name);
74         }
75     }//不能使用字面量来重写原型,否则会切断现有实例与新原型的联系
76 }
原文地址:https://www.cnblogs.com/xlzhang/p/5645550.html