Javascript封装常用方法

来源:互联网 发布:todolist软件 编辑:程序博客网 时间:2024/05/21 06:39

创建一个接口需要传入2个参数,一个name,一个是该接口包含哪些方法

var BH = {};BH.Interface = function(name,methods){    //判断接口的参数个数    if(arguments.length !=2){        throw new Error('this instance interface constructor arguments must be 2 length');    }    this.name = name;    this.methods = [];//定义一个内置的空数组对象,等待接收methods里的元素(方法名字)    for(var i=0,len = methods.length;i<len;i++){        if(typeof methods[i] !== 'string'){            throw new Error('the Interface method name is error!');        }        this.methods.push(methods[i]);    }}

验证接口的合法性,比如有没有传入真确的参数,传入的参数是否合法等

BH.Interface.ensureImplements = function (object) {    if(arguments.length <2){        throw new Error('Interface.ensureImplements method constructor arguments must be >=2;');    }    for(var i=1;i<arguments.length;i++){        var instanceInterface = arguments[i];        if(instanceInterface.constructor !== BH.Interface){            throw new Error('the arguments constructor note be Interface;');        }        //循环接口实例对象里面的每一个方法        for (var j=0;j<instanceInterface.methods.length;j++){            //用一个临时变量  接收每一个方法的名字            var methodName = instanceInterface.methods[j];            if(!object[methodName] || typeof object[methodName] !== 'function'){                throw new Error(methodName+' the method is not found!');            }        }    }} 
BH.extend = function(sub,sup){    //目的,实现只继承父类的原型对象    var F = new Function();//1.创建一个空函数  目的:空函数进行中转    F.prototype = sup.prototype;//2.实现空函数的原型对象和超类的原型对象的转换    sub.prototype = new F();//3.原型继承    sub.prototype.constructor = sub;//4.还原子类的构造器    //保存下父类的原型对象;一方面方便解耦,另一方面获得父类的原型对象    sub.superClass = sup.prototype;//自定义一个子类的静态就属性  接收父类的原型对象    //判断父类的原型对象的构造器(加保险)    if(sup.prototype.constructor == Object.prototype.constructor){        sup.prototype.constructor = sup;//手动欢迎父类原型对象的构造器    }}
/** * 单体模式   实现一个跨浏览器的事件处理程序 * @type {{}} */BH.EventUtil = {    addHandler:function (element, type, handler) {        if(element.addEventListener){//firefox            element.addEventListener(type,handler,false);        }else if(element.attachEvent){//IE            element.attachEvent('on'+type,handler);        }    },    removeHandler:function (element, type, handler) {        if(element.removeEventListener){//firefox            element.removeEventListener(type,handler,false);        }else if(element.detachEvent){//IE            element.detachEvent('on'+type,handler);        }    }}



0 0
原创粉丝点击