工厂函数与自定义构造函数

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 
 4 <head>
 5     <meta charset="UTF-8">
 6     <meta name="viewport" content="width=device-width, initial-scale=1.0">
 7     <meta http-equiv="X-UA-Compatible" content="ie=edge">
 8     <title>Document</title>
 9 </head>
10 
11 <body>
12     <script>
13         //工厂函数
14         // new函数写在函数体内,有return返回值
15 
16         /* function createObj(name, age) {
17             var obj = new Object();
18             obj.name = name;
19             obj.age = age;
20             obj.say = function say() {
21                 console.log("大家好,我是" + obj.name + ",今年" + obj.age + "岁了");
22             }
23             return obj;
24         }
25         var obj1 = createObj("张三",18);
26         var obj2 = createObj("李四",22)
27         console.log(obj1)   //{name: "张三", age: 18, say: ƒ} 打印时不显示函数名
28         obj1.say();
29         console.log(obj1.say==obj2.say) */      //地址不同
30 
31         //自定义构造函数
32         //new函数在创造的时候才写,没return,用this
33         
34         function person(name,age){
35             this.name=name
36             this.age=age
37             this.say=say
38         }
39         function say(){
40             console.log("大家好,我叫"+this.name+",今年"+this.age+"岁")
41         }
42         var obj1 = new person("尼斯",33);
43         var obj2 = new person("唐尼",39);
44         console.log(obj1)   //person {name: "尼斯", age: 33, say: ƒ} 打印时显示函数名
45         obj1.say();
46         console.log(obj1.say==obj2.say)     //地址相同
47         console.log(obj1.__proto__)     //打印结果如下
48                                         /*{constructor: ƒ}     
49                                             constructor: ƒ person(name,age)
50                                             __proto__: Object   */
51         console.log(obj1.__proto__===person.prototype)   //实例对象的__proto__与构造函数的prototype地址相同(proto:原型)
52         console.log(obj1.__proto__.constructor===person);    //每一个原型对象天生带有一个属性叫做`constructor`,这个属性指的是这个原型对象所属的构造函数
53        
54     </script>
55 </body>
56 
57 </html>

 

posted @ 2019-08-26 16:27  无人问及  阅读(195)  评论(0编辑  收藏  举报