一、面向对象 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 function creatPerson (name,qq ) { var obj = new Object (); obj.name = name; obj.qq = qq; obj.showName = function ( ) { alert(this .name); } obj.showQQ = function ( ) { alert(this .qq); } return obj; }var object = creatPerson("张三" ,95499999999 ); object.showName(); object.showQQ();`` ` ## 二、工厂方式 ` `` jsfunction creatPerson (name,qq ) { var obj = new Object (); obj.name = name; obj.qq = qq; obj.showName = function ( ) { alert(this .name); }; obj.showQQ = function ( ) { alert(this .qq); }; return obj; }var object = creatPerson("张三" ,"95499999999" );var object2 = creatPerson("李四" ,"46186465849" ); object.showName(); object.showQQ(); object2.showName(); object2.showQQ();
缺点:
没有new
函数重复->资源浪费
三、解决new的问题 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 function show ( ) { alert(this ); this .showName = function ( ) { alert("hehehe" ); } }function creatPerson (name,qq ) { this .name = name;this .qq = qq;this .showName = function ( ) { alert(this .name); };this .showQQ = function ( ) { alert(this .qq); }; }var object = new creatPerson("张三" ,"95499999999" ); object.showName(); object.showQQ();
四、原型prototype
css
对比
js
class
一次给一组元素加样式
原型
行间样式
一次给一个元素加样式
给对象加事件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 var arr1 = new Array (1 ,5 ,8 ,6 ,7 );var arr2 = new Array (11 ,25 ,58 ,16 ,17 );Array .prototype.sum = function ( ) { var result = 0 ; for (let i = 0 ; i < this .length; i++) { result+=this [i]; } return result; } alert(arr1.sum()); alert(arr2.sum());
五、类与对象 类:模子 -> Array 对象:产品(成品)-> arr
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 function creatPerson (name,qq ) { this .name = name;this .qq = qq; }var obj = CreatPerson("张三" ,"95499999999" ); alert(obj); CreatPerson.prototype.showName = function ( ) { alert(this .name); }; CreatPerson.prototype.showQQ = function ( ) { alert(this .qq); };var object1 = new CreatPerson("张三" ,"95499999999" ); object1.showName(); object1.showQQ();var object2 = new CreatPerson("李四" ,"46186465849" ); object2.showName(); object2.showQQ(); alert(object1.showName() == object2.showName());
用构造函数来加属性 行间样式 用原型来加方法 class 以上即是混合模式。