Javascript创建对象的方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 | <!DOCTYPE html> <html> <head> <meta http-equiv= "Content-Type" content= "text/html; charset=utf-8" /> <title></title> <script src= "jquery-1.9.1.js" ></script> <meta charset= "utf-8" /> </head> <body> <button id= "btn" >提交</button> </body> <script> $( '#btn' ).click( function (){ //通过object创建对象 var person = new Object(); person.name= 'wj' ; person.job= 'c#.net' ; person.fn= function (){ console.log( this .name+ this .job); }; // person.fn(); //通过字面量创建对象 var conmpany={ name: "fanyaunwang" , salary: "6500" , fn: function (){ console.log( this .name+ this .salary); } }; //conmpany.fn(); //以上2种方式创建对象,会产生大量的重复代码 //通过工厂模式创建对象 // 工厂模式减少了代码重复,但是不能识别对象,所有的实例都是object类型 function createObject(name,age,job) { var o = new Object(); o.name=name; o.age=age; o.job=job; o.fn= function (){ console.log( this .name+ this .job+ this .age); } return o; } //var wj=createObject('wj','22','c#.net'); //wj.fn(); //通过构造函数创建对象 //构造函数中首字母大写,而非构造函数首字母小写作为区别 function CreatePerson(name,age,job) { this .name=name; this .age=age; this .job=job; this .fn= function (){ console.log( this .name+ this .age+ this .job); } } //通过new来创建CreatePerson实例,这样创建的实例都有一个constractor //属性指向CreatePerson //通过工厂模式创建的对象都是object,无法判读对象的类型, //但是通过构造函数创建的对象可以,这是构造函数创建对象胜过 //通过工厂模式创建对象的地方 var obi= new CreatePerson( 'wangjun' , '23' , 'c#.net' ); obi.fn(); console.log(obi.constructor==CreatePerson); //true //通过原型模式来创建对象 //原型模式就是在构造函数中吧方法拿出来的基础上,在做了一层封装 function Employee(){ } Employee.prototype.name= 'wangjun' ; Employee.prototype.age= 'c#' ; Employee.prototype.fn= function (){ console.log( this .name+ this .age); } var emp= new Employee(); var emp1= new Employee(); emp.fn(); emp1.fn(); //这个fn是公共的 console.log(emp.fn()==emp1.fn()); //true //在构造函数创建对象的模式中是false //构造函数和原型混合模式 //创建自定义类型的最常见方式 //构造函数模式用于定义实例属性, //原型模式用于定义公共属性 function Customer(name,address) { this .name=name; this .address=address; this .phone=[ '13946' , '44848484' ]; } Customer.prototype={ constructor:Customer, p:[ 'af' , 'sfasf' ], fnn: function (){ console.log( this .name+ 'prototype' ); } } var objc= new Customer( 'fanyuanwang' , 'shenzheng' ); var obje= new Customer( 'wangjin' , 'changsha' ); console.log(objc.phone==obje.phone); //false //上面这个就是构造函数的引用类型的不同 objc.fnn(); console.log(objc.fnn==obje.fnn); //true objc.fnn(); }); </script> |
本文作者:WangJunZzz
本文链接:https://www.cnblogs.com/WangJunZzz/p/7352565.html
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步