面向对象编程(OOP)----BLUE大师JS课堂笔记(二)
一,把面向過程的程序改寫成面向?qū)ο蟮某绦?/p>
1.前提 ? 所有的程序都在onload里面
2.改寫 ? 不能函數(shù)嵌套,可以全局變量
3.onload-------------------->構(gòu)造函數(shù)
? 全局變量------------------->屬性
? 函數(shù)----------------------->方法
? 需要用到面向?qū)ο蟊容^多的是游戲公司
4.改錯(cuò),重點(diǎn)是this
? this啥時(shí)候出問題呢?1.定時(shí)器 ? 但凡定時(shí)器中的this都是指的是window
? ? ? ? ? ? ? ? ? ? ? ? ? ? ?2.事件
? 解決這個(gè)方法 ? var _this=this;
? 然后通過閉包傳遞this
?
二,JSON更適合只生成一個(gè)JSON對(duì)象的情況
? ? ?命名空間:JSON里面套JSON
? ? ?var obj = {a:5,b:12,c:function(){
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? alert(this.a);
? ? ? ? ? ? ? ? ? ?},d:{e:function(){
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?alert(this.f);
? ? ? ? ? ? ? ? ? ? ? ? ?},f:34}};
?
三,繼承
在PHP中表現(xiàn)繼承的方式如下:
1 class Person{ 2 function __construct($name,$sex) 3 { 4 $this->name=$name; 5 $this->sex=$sex; 6 } //定義類的屬性 7 function showName() 8 { 9 echo $this->name; //定義類的showName方法 10 } 11 function showSex() 12 { 13 echo $this->sex; //定義類的showSex方法 14 } 15 } 16 17 class Worker extends Person{ 18 function __construct($name,$sex,$job) 19 { 20 parent::__construct($name,$sex); //調(diào)用Person構(gòu)造 函數(shù),繼承Person 21 } 22 }
在這個(gè)過程中,分為兩部,一,定義Person類的屬性和方法 ?二,定義worker類,并調(diào)用Person類(繼承)
?
JS中的繼承與這個(gè)過程類似:先執(zhí)行父級(jí)的構(gòu)造函數(shù),然后再添加子類的屬性和方法
?
JS中的繼承的寫法:
1 function Person(name,sex) 2 { 3 this.name=name; 4 this.sex=sex; 5 } //定義構(gòu)造函數(shù) 6 Person.prototype.showName=function() 7 { 8 alert(this.name); 9 }; //添加showName方法 10 Person.prototype.showSex=function() 11 { 12 alert(this.Sex); 13 }; //添加showSex方法 14 15 function Worker(name,sex,job) 16 { 17 Person.call(this,name,sex); //構(gòu)造函數(shù)偽裝,把Worker實(shí)例偽裝成Person實(shí)例,來繼承Person的屬性 18 this.job=job; //單獨(dú)定義自己的屬性 19 } 20 21 Worker.prototype=Person.prototype; //把Person.prototype指針賦給Worker.prototype 22 23 Worker.prototype.showJob=function() 24 { 25 alert(this.job); 26 }; //定義自己的方法
call改變函數(shù)執(zhí)行的this
在JS中全部對(duì)象都是引用,因此上面這段代碼中的21行Worker.prototype=Person.prototype;是引用的一個(gè)對(duì)象,當(dāng)
Worker.prototype.showJob=function() { alert(this.job); };
給Worker.prototype.showJob時(shí)就相當(dāng)于Person.prototype也有showJob方法了,這樣不好,把父級(jí)都給覆蓋了,因此為了解決這個(gè)問題要想辦法不要把對(duì)象引用要復(fù)制,通過下面這段代買就能很好地解決這個(gè)問題
for(var attr in Person.prototype) {Worker.prototype[attr]=Person.prototype[attr]; }
這樣就相當(dāng)于把Person.prototype復(fù)制了一份給Worker.prototype,這樣給Worker.prototype加一個(gè)方法就不會(huì)影響到Person.prototype了。
而如果整站都需要作出改變,那只要修改父級(jí)就可以了,這樣會(huì)很方便,不容易出錯(cuò)。
?
四,instanceof ? ? ...是...的實(shí)例
五,系統(tǒng)對(duì)象:1,本地對(duì)象(非靜態(tài)對(duì)象):需要實(shí)例,需要new ?-----------Object,Function,Array,String,Boolean,Number,RegExp,Error
? ? ? ? ? ? ? ? ? ? 2.內(nèi)置對(duì)象(靜態(tài)對(duì)象): ? 不需要實(shí)例化,直接可以用,不需要new -------------global ? ? Math
? ? ? ? ? ? ? ? ? ? 3.宿主對(duì)象:BOM DOM
轉(zhuǎn)載于:https://www.cnblogs.com/ggbd-lie/archive/2012/11/22/2782651.html
總結(jié)
以上是生活随笔為你收集整理的面向对象编程(OOP)----BLUE大师JS课堂笔记(二)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 哥字开头的成语有哪些啊?
- 下一篇: C++Primer学习笔记(二)