如何写一个JavaScript 的插件

基础写法

一、JQuery风格写法

防止参数污染到整体环境。

1、基础写法
;(function(global,factory){
	factory(global)
})(this,function(window){
	var Test = "cjx - in";
	window.Test = Test;
	console.log(window)
})
复制代码
2、一般写法
;(function(global,factory){
	factory(global)
})(this,function(window){
	function Person(){
		this.personer = "陈"; 
	}
	Person.prototype.getValue=function(){return this.personer;};
	var P = new Person();
	window.P = P;
	console.log(window)
})
console.log(P); //Person {personer: "陈"}
console.log(P.getValue()); //"陈"
复制代码
3、基于Jquery,bootstrap(html,css)编写自检查表单验证
//bv===bootstrapValigage
<form id="mForm" class="form-container form-horizontal" action="" method="get">
  <div class="form-group">
    <label for="inputEmail3" class="col-sm-2 control-label">Email</label>
    <div class="col-sm-10">
      <input type="email" class="form-control" id="email" placeholder="Email"
		data-bv-required="true"
		data-bv-required-error="不能为空"
		data-bv-email="true"
		data-bv-email-error="当前email不能为空"
      >
    </div>
  </div>
  <div class="form-group">
    <label for="inputPassword3" class="col-sm-2 control-label">Password</label>
    <div class="col-sm-10">
      <input data-bv-required="true" type="password" class="form-control" id="password" 
      	data-bv-required="true"
      	data-bv-required-error="不能为空"
      	data-bv-regex="^\w{6,16}$"
      	data-bv-regex-error="6到16位随机"
      >
    </div>
  </div>
  <div class="form-group">
    <div class="col-sm-offset-2 col-sm-10">
      <button type="button" data-bv-type="submit" class="btn btn-primary upMessbtn">Sign in</button>
      <button type="reset" class="btn btn-warningj">Reset</button>
    </div>
  </div>
</form>
<!--引入js文件-->
<script>
    $("#mForm").bootstrapValidator({raise:"keyup"});
</script>
复制代码
;(function(global,factory,plug){
	return factory.call(global,global.jQuery,plug)
})(this,function($,validator){
	//默认常量
	const __DEFS__ = {
		raise:"change",//默认值
		error:"error 不匹配",//默认值
	};
	const __RULES__ = {
		"required":function(){
			let val = this.val();
			return val!=""&&val!=undefined&&val!=null;
		},//必填项
		"email":function(){
			return /^[A-Za-z0-9._%-]+@([A-Za-z0-9-]+\.)+[A-Za-z]{2,4}$/.test(this.val());
		},//邮件格式
		"mobile":function(){
			return false;
		},//坐机号码
		"phone":function(){
			return false;
		},//手机号码
		"number":function(){
			return false;
		},//数字
		"amount":function(){
			return false;
		},//金额
		"regex":function(regex){
			return new RegExp(regex).test(this.val());
		},//正则表达式格式
		"length":function(){
			return false;
		}
	}
	//闭包中
	$.fn[validator] = function(ops=__DEFS__){
		if(!this.is("form")){
			throw new Error("type error[require form tag]");
		}
		const [$form,that] = [$(this),this]; //保留form 表单以用于提交
		// $.extend(this,__DEFS__,ops);//扩展属性和功能
		//dom.getAttribute元素 和 $dom.attr
		//健壮性,开闭原则
		this.$fields = this.find("input,textarea,select").not("input[type='reset'],input[type='submit'],input[type='image'],input[type='button']");
		this.$fields.map((index,item)=>{
			$(item).data("check", false);
		})
		this.$fields.on(ops.raise,function(){
			let $field = $(this);
			let [config,error,__err__] = ["","",true]; //校验结果默认为true
			let $group = $field.parents(".form-group");//父元素
			$group.removeClass("has-success has-error");
			$group.find(".help-block").remove();
			$.each(__RULES__,function(rule,valid){
				config = $field.data("bv-"+rule);
				if(config){
					__err__ = valid.call($field,config);
					$group.addClass(__err__?"has-success":"has-error");
					if(!__err__){
						error = $field.data("bv-"+rule+"-error")||that.error;
						$field.after(`<span class="help-block">${error}</span>`);
					}
					return __err__;
				}
			});
			__err__?$field.data("check",true):$field.data("check",false);
		})
		//禁止提交
		this.$upbtns = this.find("button[type='button']").filter(function(){return $(this).data("bv-type")=="submit"});
		this.$upbtns.on("click",function(){
			if(!(that.$fields.toArray()).every(function(item, index, array){return $(item).data("check")==true;})){return false;}
			$form.submit();
		})
		this.on("keydown",function(){if(event.keyCode==13){that.$upbtns.eq(0).trigger("click")}}); //禁用提交
	}
},"bootstrapValidator");

// 依托于jquery from表单拓展 类似于bootstrap

复制代码

二、单例写法

!(function () {
    //管理单例的逻辑代码,如果没有数据则创建,有数据则返回
   var getSingle = function(fn){ //参数为创建对象的方法
       var result;
       return function(){ //判断是Null或赋值
           return result || (result = fn.apply(this,arguments));
       };
   };
    //创建登录窗口方法
    var createLoginLayer = function(){
        var div = document.createElement('div');
        div.innerHTML = '我是登录浮窗';
        div.style.display = 'none';
        document.body.appendChild(div);
        return div;
    };
    //单例方法
    var createSingleLoginLayer = getSingle(createLoginLayer);

    //使用惰性单例,进行创建
    document.getElementById('loginBtn').onclick = function(){
        var loginLayer = createSingleLoginLayer();
        loginLayer.style.display = 'block';
    };
})()
//自执行方法
复制代码

三、调用父类构造函数

!(function () {
    var A = function (light) {
        this.light1 = light;
    };
    var B = function (light) {
        this.light = light;
        A.apply(this,arguments);//你需要手动调用A的构造方法
    };
    //给B赋值的同时,给A赋值
    B.prototype = new A();
    var C = new B(123);
    console.log(C.light);
    console.log(C.light1);
})()
复制代码

四、策略模式

定义一系列的算法,把它们一个一个封装起来。将算法的使用与算法的实现分离开来。

!(function () {
    //定义算法方法
    var strategies = {
        "S":function(salary){
          return salary * 4;
        },
        "A":function(salary){
            return salary * 3;
        },
        "B":function(salary){
            return salary * 2;
        }
    };
    //执行算法
    var calculateBouns = function(level,salary){
      return strategies[level](salary);
    };
    console.log(calculateBouns('S',2000));
})() 
复制代码

转载于:https://juejin.im/post/5cda7473e51d453a506b0f0a

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值