zoukankan      html  css  js  c++  java
  • 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
  • 相关阅读:
    写了一个分页控件。
    职业规划
    程序员该做的事
    做就做最优秀的员工
    Tomcat+JSP经典配置实例
    2005年11月26日8点50左右,南昌地震。
    如何添加一个自定义的columnstyles 到设计器中,以便在设计时直接使用他们?
    Oracle 的入门心得【强烈推荐】
    如何随机显示记录条数的15% ?
    重写DataGrid的DataGridBoolColumn,添加bool值改变事件。
  • 原文地址:https://www.cnblogs.com/potato-lee/p/8810186.html
Copyright © 2011-2022 走看看