<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>prototype与OOP</title> <script type="text/javascript"> //-------------------------------------------01 Object var obj = new Object(); obj.name = 'Angle'; obj.qq = '13123265'; obj.showName = function(){ alert('my name is ' + this.name); }; obj.showQQ = function(){ alert('my qq is ' + this.qq); }; //obj.showName(); //obj.showQQ(); //-------------------------------------------02 Object工厂方式(一般不用) //缺陷:每一对象都有一套自己的属性和方法,函数重复,资源浪费 alert(obj1.showName == obj2.showName)--false function createPerson(name,qq) { //原料 var obj = new Object(); //加工 obj.name = name; obj.qq = qq; obj.showName = function(){ alert('my name is ' + this.name); }; obj.showQQ = function(){ alert('my qq is ' + this.qq); }; //出厂 return obj; } var obj1 = createPerson('guo','1313298765'); var obj2 = createPerson('jiang','2313298765'); //obj1.showName(); //obj2.showQQ(); //-------------------------------------------03 Object 工厂方式 new方式 function createPerson2(name,qq) { //var this = new Object();系统偷偷做 this.name = name; this.qq = qq; this.showName = function(){ alert('my name is ' + this.name); }; this.showQQ = function(){ alert('my qq is ' + this.qq); }; //return this;系统偷偷做 } var obj3 = new createPerson2('guo','1313298765'); var obj4 = new createPerson2('jiang','2313298765'); //obj3.showName(); //obj4.showQQ(); //-------------------------------------------04 Object 原型prototype //CSS JS //class 一次给一组元素加样式 原型 //行间样式 一次给一个元素加样式 给对象加事件 var arr1 = new Array(1,2,3,4,5,6); var arr2 = new Array(11,12,13,14,15,16); Array.prototype.mySum = function () { var result = 0; for(var i=0;i<this.length;i++) { result += this[i]; } return result; }; //alert(arr1.mySum()); //alert(arr2.mySum()); //-------------------------------------------05 Object 原型+new混合方式(日常基本都这样写) //在构造函数里面加属性,在原型里面加方法 //构造函数名就是自定义类名,所以首字母最好大写 function CreatePerson3(name,qq) { this.name = name; this.qq = qq; } CreatePerson3.prototype.showName = function(){ alert('my name is ' + this.name); }; CreatePerson3.prototype.showQQ = function(){ alert('my qq is ' + this.qq); }; var obj5 = new CreatePerson3('guo','1313298765'); var obj6 = new CreatePerson3('jiang','2313298765'); alert(obj5.showName==obj6.showName); //true 节省资源 </script> </head> <body> </body> </html>