JS 原型模式 工厂模式 构造函数的区别

原型模式 工厂模式 构造函数的区别,看代码:

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>OOP</title>
 6 </head>
 7 <body>
 8 <script type="text/javascript">
 9 
10 /*---@原型模式--
11 */
12 function Person1(){  //构造函数,空的
13 }
14 Person1.prototype.name = "Nicholas"; //每个函数都有一个prototype的属性
15 Person1.prototype.age = 29;//这里不能把Person1换成this
16 Person1.prototype.job = "Software Engineer";
17 Person1.prototype.sayName2 = function(){
18 document.write("<br/>原型模式"+this.name);//这里是this
19 };
20 var person1 = new Person1();
21 person1.sayName2(); //"Nicholas"
22 console.log(person1.sayName2 instanceof Object); //true
23 console.log(Person.prototype);//Object
24 
25 
26 
27 //@--工厂模式
28 /*1.要在函数内部new一个实例化对象;
29   2.有返回值,返回new的那个对象;
30   3.函数名首字母最好不要大写,因为构造函数函数名必须是大写;
31  */
32 function createPerson() {
33     var o=new Object();//**这里的Object首字母大写了
34     o.name = "plant";
35     o.age = 29;
36     o.job = "Software Engineer";
37     o.sayName = function () {
38         document.write("<br/>工厂模式:"+o.name);
39     };
40     return o;
41 }
42 var person1 = new createPerson();
43 person1.sayName();
44 
45 
46 /*----@构造函数---
47   1.可以使用this来指向当前作用域中的对象;
48   2.函数名首字母移到要大写;
49   3.无返回值;
50  */
51 function Person(name,age,job){
52     this.name=name;
53     this.age=age;
54     this.job=job;
55     this.sayName1=function(){
56         document.write("<br/>构造函数的输出"+this.name);
57     }
58 };
59 
60 var pp1=new Person("hynix",31,"Big data");
61 pp1.sayName1();
62 </script>
63 </body>
64 </html>
View Code

 

posted @ 2018-04-12 20:18  potato~e-e  阅读(339)  评论(0编辑  收藏  举报