標籤:javascript 瀏覽器 function without 探測器
<script>/*所有探測器都有探測的方法和分析的方法,分析當前的瀏覽器環境,不管是瀏覽器還是nodejs*//*container容器探測器*//*link連結探測器*//*外層用一個立即執行的匿名函數包裹住,防止一些函式宣告或者變數泄露到外面*/!function(global){ function DetectorBase(configs){//不讓外部通過直接調用方式調用,必須使用new,不使用new就會報錯 /*使用new的話,this就是最後要返回的對象,this instanceof DetectorBase應該返回true,不是的話說明沒有直接通過new調用*/ if(!this instanceof DetectorBase){/**/ throw new Error(‘Do not invoke without new.‘); } this.configs=configs;/*所有的探測器都會有config屬性*/ this.analyze();/*所有的探測器初始化的時候都需要解析一下資料*/ } DetectorBase.prototype.detect=function(){/*代表一個抽象的探測方法,基類不是具體的一個探測器所以實現沒有意義,用來說明需要實現這樣一個方法*/ throw new Error(‘Not implemented‘); } DetectorBase.prototype.analyze=function(){ console.log(‘analyzing...‘); this.data="###data###"; } /***具體執行個體***/ function LinkDetector(links){/*連結探測器,同理必須通過new來構造*/ DetectorBase.apply(this,arguments); if(!this instanceof LinkDetector){ throw new Error(‘Do not invoke without new.‘); } this.links=links; } function ContainerDetector(containers){ DetectorBase.apply(this,arguments); if(!this instanceof ContainerDetector){ throw new Error(‘Do not invoke without new.‘); } this.containers=containers; } //inherit first /*LinkDetector和ContainerDetector都可能掛載一些自己的方法 需要注意,一定要先實現原型鏈的繼承,再去擴充。 因為繼承的時候要改寫LinkDetector的prototype屬性*/ inherit(LinkDetector,DetectorBase); inherit(ContainerDetector,DetectorBase); //expand later LinkDetector.prototype.detect=function(){ console.log(‘Loading data:‘+this.data); console.log(‘Link detection started.‘); console.log(‘Scaning links:‘+this.links); } ContainerDetector.prototype.detect=function(){ console.log(‘Loading data:‘+this.data); console.log(‘Container detection started.‘); console.log(‘Scaning containers:‘+this.containers); } //prevent from being altered /*不希望監控程式被改寫,不可刪,不可擴充,不可寫*/ Object.freeze(DetectorBase); Object.freeze(DetectorBase.prototype); Object.freeze(LinkDetector); Object.freeze(LinkDetector.prototype); Object.freeze(ContainerDetector); Object.freeze(ContainerDetector.prototype); //export to global object /*通過defineProperties一次性把3個類暴露在外面,同時保護它們不可被枚舉,不可被刪除和改寫*/ Object.defineProperties(global,{ LinkDetector:{value:LinkDetector}, ContainerDetector:{value:ContainerDetector}, DetectorBase:{value:DetectorBase} }); function inherit(subClass,superClass){// subClass.prototype=Object.create(superClass.prototype); subClass.prototype.constructor=subClass; }}(this);var cd=new ContainerDetector(‘#abc #def #ghi‘);var ld=new LinkDetector(‘http://www.taobao.com http://www.tmall.com http://www.baidu.com‘);cd.detect();ld.detect();</script>
650) this.width=650;" src="/img/fz.gif" alt="複製代碼" style="margin:0px;padding:0px;border:none;" />
運行結果:
650) this.width=650;" src="http://images2015.cnblogs.com/blog/315302/201701/315302-20170110145246072-336820673.png" style="margin:0px;padding:0px;border:0px;" />
javascript OOP執行個體—探測器