oop编程 探测器实例

来源:互联网 发布:淘宝店铺改名字怎么改 编辑:程序博客网 时间:2024/06/10 06:20
//让他通过new来调用这个函数。//判断一下:this instanceof DetectorBase//如果不是new来调用的,会返回false;//如果是new来调用的,会返回true。//基类没有detect方法,所以要抛出异常。//要先继承再扩充子类的一些方法什么的。//因为先扩充的话,会把之前的覆盖掉。//定义多个属性 defineProperties//基类,能立即执行的函数,this指向window/global!function(global){    function DetectorBase(configs){        if(!this instanceof DetectorBase){            throw new Error('Do not invoke without new.');        }        this.configs=configs;        this.analyze();    }    DetectorBase.prototype.detect = function() {        // body...        throw new Error('Not implemented.');    };    DetectorBase.prototype.analyze=function(){        console.log('analyzing……');        this.data='###data###';    }//链接探测器function LinkDetector(links){    if(!this instanceof LinkDetector){        throw new Error('Do not invoke without new.');    }    this.links=links;    //调用基类    DetectorBase.apply(this,arguments);}//内容探测器function ContainerDetector(containers){    if (!this instanceof ContainerDetector) {        throw new Error('Do not invoke without new.');    };    this.containers=containers;    DetectorBase.apply(this,arguments);}//先继承inherit(LinkDetector,DetectorBase);inherit(ContainerDetector,DetectorBase);//初始化参数function inherit(subClass,superClass){    subClass.prototype=Object.create(superClass.prototype);    subClass.prototype.constructor=subClass;    //让subClass.prototype指向subClass}//再扩充子类函数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('Link detection started.');    console.log('Scaning containers:'+this.containers );}//阻止别人修改基类和子类Object.freeze(DetectorBase);Object.freeze(DetectorBase.prototype);Object.freeze(LinkDetector);Object.freeze(LinkDetector.prototype);Object.freeze(ContainerDetector);Object.freeze(ContainerDetector.prototype);//自定义探测器的属性,只有value,其他标签默认都是falseObject.defineProperties(global,{    LinkDetector:{value:LinkDetector},    ContainerDetector:{value:ContainerDetector},    DetectorBase:{value:DetectorBase}});}(this);var cd=new ContainerDetector('#abc #def #ghi');var ld=new LinkDetector('http://www.w3cschool.com');cd.detect();ld.detect();




0 0
原创粉丝点击