前端学习之JavaScript面向对象(1)——封装

1、js面向对象的概念(个人理解)
(1)面向对象,即OOP(Object Oriented Programming),是计算机的一种编程架构,OOP的基本原则是计算机是由子程序作用的单个或者多个对象组合而成,包含属性和方法的对象是类的实例,但是JavaScript中没有类的概念,而是直接使用对象来实现编程。
(2)js面向对象是一种思想,在我的理解中,对象由属性和方法组成。属性可以理解为对象特征的载体,是静态的;方法可以理解为对象的行为,是动态的。比如:在汽车这个对象中,它的颜色,型号,大小就是它的属性,而行驶则是他的方法。
(3)在js中,所有的对象可以分为普通对象和函数对象。而Object ,Function 是JS自带的函数对象。凡是通过 new Function() 创建的对象都是函数对象,其他的都是普通对象。
以上是我个人的理解,js面向对象的知识点包括封装、继承和多态等,今天我先用一个小例子分享一下封装,后续的博文会更新继承和多态。
关于js面向对象可以看看这篇文章:https://blog.csdn.net/lihangxiaoji/article/details/79753473
那在js中怎么创建和操作对象呢,下面通过代码来一看究竟:

                //三大类型
				//1.Array(数组类型)
				//(1).使用Array构造函数
				var arr = new Array();
				arr[0] = 'a';
				arr[1] = 'b';
				var arr2 = new Array('x','y','z');
				//(2).使用字面量表示法
				var arr3 = ['red','green','yellow'];
				console.log(arr);
				//2.object类型
				//(1)、object构造函数
				var person = new Object();
				person.name = 'zjk';
				//person[age] = 18; 没有引号
				person['age'] = 18;
				console.log(person);
				//(2)、使用字面量表示法
				//A.简单字面量
				var person2 = {};
				person2.name = 'jack';
				person2.action = function(){
					console.log(this.name);
				}
				//B.嵌套字面量 项目中用的最多
				var person3 = {
					name:"black jack",//name如果是保留字、有连接符/空格,则要'name-p'
					age:20,
					action:function(){
						console.log(this.name);
					}
					
				};
				//(3)、工厂方式
				function createObj(name){
					var obj = new Object()
					obj.name = name;
					obj.showName = function(){console.log(this.name)};
					return obj;
					
				};
				var p =  createObj('aa');
				p.showName();
				//(4).构造函数 驼峰命名
				function CreateObj2(name){
					this.name = name;
					this.showName = function(){console.log(this.name)};
				};
				var p2 = new CreateObj2('大米');
				p2.showName();
				
			var person1 = {
			  age:20
      }
            var person2 = person1;
			person2.age = 23;
			console.log(person1.age = person2.age)// true
			}
			var a = {age:22}
			var b = a;
			a = 1;
			console.log(b);

再来看看对象属性有哪些操作:

            //1.1属性的添加  --> . / []
			//二者区别:.是取自身的属性;[]可以是变量
			var obj = {};
			obj.name = "zjk";
			obj["age"] = 20;
			//实例
			var obj2 = {};
			obj2.name = "jack";
			obj2.a = "aaa";
			var a = 'name';
			console.log(obj2['a']);//aaa
			console.log(obj2[a]);//obj2['name']
			//1.2属性删除
			var obj3 = {};
			obj3.name = 'zjk';
			obj3.age = 20;
			obj3.state = false;
			delete obj3.name;//删除name属性  obj3['name']
			//2.检测属性  判断对象中是否存在该属性
			// in 运算符  继承过来的也能获取到
			var obj4 = {
				name:'zjk',
				age:20
			};
			console.log('name' in obj4);
			//hasOwnroperty()方法
			var obj5 = {
				name:'zjk',
				age:20
			};
			obj5.hasOwnProperty('name');
			var a = 'name';
			obj5.hasOwnProperty(a);
			//!=undefined 值的判断
			console.log(obj5.name !=undefined);//=赋值;==判断(比较两个值是否匹配,不进行类型匹配);===全等(两个值要要进行类型匹配)
			//3.枚举属性
			//(1).for in
			
			var o = {
				name:'zjk',
				age:20
			};
			for(var a in o){//for(属性 in 对象)
				console.log(a);//name age
				console.log(o[a])//zjk 20
			}
			var arr = ['a','b','c','d'];
			for(var a in arr){
				console.log(a);//获取索引
				console.log(arr[a]);//获取值
			}
			//(2)forEach()  这个也是常用的一个遍历数组的方法
			var arr2 = ['a','b','c','d'];
			arr2.forEach(function(item,index){
				console.log(item);
				//return item 不行
			});
			//(3)map() 回调函数中支持return返回值 用的多
			var arr3 = ['a','b','c','d'];
			arr3.map(function(item,index){
				console.log(item);
				return item ;
			});
			//for()
			//4.序列化 JSON.parse()//对象字符串转为对象(深拷贝)  JSON.stringity()//对象转为对象字符串
			var o = {//这是一个对象
				name:'zjk',
				age:20
			};
			console.log(typeof JSON.stringify(o));//string  对象转化为对象字符串
			console.log(typeof o);//object

对js面向对象有所了解后,我们来看个简单的,但也是项目中百分百会做碰到例子——表单校验,在学过面向对象后,要逐渐地把以前面向过程式开发转向面向对象。我在这里放了三个封装程度不同的版本,还有过程式开发的,我们一起来看看:

过程式

$(function(){
    //正则
	// var filter  = /^[\u4e00-\u9fa5]{2,4}$/;
    // var filter  = /^((\+?86)|(\(\+86\)))?(13[012356789][0-9]{8}|15[012356789][0-9]{8}|18[02356789][0-9]{8}|147[0-9]{8}|1349[0-9]{7})$/;
    //var filter  = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
    

    //1、成为焦点  错误提示框隐藏
    $(".list li input").on('focus',function(){
        $(this).siblings(".tip-error").hide();  //find()   next()   siblings()
    });
    
    //2、失去焦点       1)为空判断   2)格式匹配(正则)
    $(".list .name").blur(function(){
        var cur = $(this);
        var value = cur.val();
        var filter  = /^[\u4e00-\u9fa5]{2,4}$/;   //正则
        fromEvent (cur,value,filter,'用户名不能为空','用户名输入错误');
    });
    $(".list .mobile").blur(function(){
        var cur = $(this);
        var value = cur.val();
        var filter  = /^((\+?86)|(\(\+86\)))?(13[012356789][0-9]{8}|15[012356789][0-9]{8}|18[02356789][0-9]{8}|147[0-9]{8}|1349[0-9]{7})$/;   //正则
        fromEvent (cur,value,filter,'手机号不能为空','手机号输入错误');
    });
    $(".list .email").blur(function(){
        var cur = $(this);
        var value = cur.val();
        var filter  = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;   //正则
      
        fromEvent (cur,value,filter,'邮箱不能为空','邮箱输入错误');
    });
    //公共方法
    function fromEvent (cur,value,filter,text1,text2){
        if(value ==''){
            cur.siblings(".tip-error").show().text(text1);
        }else if(!filter.test(value)){   //正则匹配
             cur.siblings(".tip-error").show().text(text2);
        }else {
            cur.siblings(".tip-error").hide();
        }
    };
    //3、提交 (AJAX)
    $(".list .btn-submit").on('click',function(){
        var _name = $.trim($(".name").val()),
            _mobile = $.trim($(".mobile").val()),
            _email = $.trim($(".email").val()),
            _age = $.trim($(".age").val()),
            _address = $.trim($(".address").val());
        var data ={
            name:_name,
            mobile:_mobile,
            email:_email,
            age:_age,
            address:_address
        };
        if(_name==''|| _mobile=='' || _email =='' || $(".tip-error").is(":visible")) {
            alert("请输入正确信息");
        }else {
            $.ajax({
                type: "POST", //请求方式
                url: "http://localhost:3000/form_info", //请求路径
                async: true, //异步
                data: data,  //传参
                dataType: 'json', //返回值类型
                success: function (msg) {
                    if(msg.code =='200'){
                        
                    }
                },
                error: function () {
                }
            });
        }   
    })
})

封装一(我最喜欢的)

var obj = {
    init:function(){
        this.bind();
        this.todoAjax();
    },
    bind:function(){
        var self = this;
        //1、成为焦点  错误提示框隐藏
        $(".list li input").on('focus',function(){
            $(this).siblings(".tip-error").hide();  //find()   next()   siblings()
        });
        //2、失去焦点       1)为空判断   2)格式匹配(正则)
        $(".list input").blur(function () {
            var name = $(this).prev().text();
            var reg;
            switch ($(this).attr("name")) {
                case "name":
                    reg = /^[\u4e00-\u9fa5]{2,4}$/;
                    break;
                case "mobile":
                    reg = /^((\+?86)|(\(\+86\)))?(13[012356789][0-9]{8}|15[012356789][0-9]{8}|18[02356789][0-9]{8}|147[0-9]{8}|1349[0-9]{7})$/;
                    break;
                case "email":
                    reg = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
                    break;
                case "age":
                    reg = /^(?:[1-9]?\d|100)$/;
                    break;
            }
            self.formEvent($(this), $(this).val(), name, reg);
        });
    },
  formEvent:function(cur,value,name,reg) {
    if(value ==''){
      cur.siblings(".tip-error").show().text(name + "不能为空!");
    }else if(!reg.test(value)){   //正则匹配
      cur.siblings(".tip-error").show().text(name + "输入错误!");
    }else {
      cur.siblings(".tip-error").hide();
    }
  },
    todoAjax:function (){
        $(".list .btn-submit").on('click',function(){
            var _name = $.trim($(".name").val()),
                _mobile = $.trim($(".mobile").val()),
                _email = $.trim($(".email").val()),
                _age = $.trim($(".age").val()),
                _address = $.trim($(".address").val());
            var data ={
                name:_name,
                mobile:_mobile,
                email:_email,
                age:_age,
                address:_address
            };
            if(_name==''|| _mobile=='' || _email =='' || $(".tip-error").is(":visible")) {
                alert("请输入正确信息");
            }else {
                $.ajax({
                    type: "POST", //请求方式
                    url: "http://localhost:3333/getlist", //请求路径
                    async: true, //异步
                    data: data,  //传参
                    dataType: 'json', //返回值类型
                    success: function (msg) {//msg 响应数据
                        if(msg.code =='200'){
                            
                        }
                    },
                    error: function () {
                    }
                });
            }   
        })
    }
}
$(function(){
    obj.init();
})

封装二


    var obj = {
        init:function(){
            this.bind();
            this.todoAjax();
        },
        formEvent:function(cur,value,filter,text1,text2){
            if(value ==''){
                cur.siblings(".tip-error").show().text(text1);
            }else if(!filter.test(value)){   //正则匹配
                 cur.siblings(".tip-error").show().text(text2);
            }else {
                cur.siblings(".tip-error").hide();
            }
        },
        bind:function (){
            var self = this;
            //1、成为焦点  错误提示框隐藏
            $(".list li input").on('focus',function(){
                $(this).siblings(".tip-error").hide();  //find()   next()   siblings()
            });
            //2、失去焦点       1)为空判断   2)格式匹配(正则)
            $(".list .name").blur(function(){
                var cur = $(this);
                var value = cur.val();
                var filter  = /^[\u4e00-\u9fa5]{2,4}$/;   //正则
                self.formEvent (cur,value,filter,'用户名不能为空','用户名输入错误');
            });
            $(".list .mobile").blur(function(){
                var cur = $(this);
                var value = cur.val();
                var filter  = /^((\+?86)|(\(\+86\)))?(13[012356789][0-9]{8}|15[012356789][0-9]{8}|18[02356789][0-9]{8}|147[0-9]{8}|1349[0-9]{7})$/;   //正则
                self.formEvent (cur,value,filter,'手机号不能为空','手机号输入错误');
            });
            $(".list .email").blur(function(){
                var cur = $(this);
                var value = cur.val();
                var filter  = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;   //正则
                if(value ==''){
                    $(this).siblings(".tip-error").show().text("邮箱不能为空");
                }else if(!filter.test(value)){   //正则匹配
                     $(this).siblings(".tip-error").show().text("邮箱输入错误");
                }else {
                    $(this).siblings(".tip-error").hide();
                };
                self.formEvent (cur,value,filter,'邮箱不能为空','邮箱输入错误');
            });
        },
        todoAjax:function (){
            $(".list .btn-submit").on('click',function(){
                var _name = $.trim($(".name").val()),
                    _mobile = $.trim($(".mobile").val()),
                    _email = $.trim($(".email").val()),
                    _age = $.trim($(".age").val()),
                    _address = $.trim($(".address").val());
                var data ={
                    name:_name,
                    mobile:_mobile,
                    email:_email,
                    age:_age,
                    address:_address
                };
                if(_name==''|| _mobile=='' || _email =='' || $(".tip-error").is(":visible")) {
                    alert("请输入正确信息");
                }else {
                    $.ajax({
                        type: "POST", //请求方式
                        url: "http://localhost:3333/getlists", //请求路径
                        async: true, //异步
                        data: data,  //传参
                        dataType: 'json', //返回值类型
                        success: function (msg) {
                            if(msg.code =='200'){
                                
                            }
                        },
                        error: function () {
                        }
                    });
                }   
            })
        }
    }
$(function(){
    obj.init();
})

封装三

function base () {
    var self = this;
    this.blur_name = function(){
        var cur = $(this);
        var value = cur.val();
        var filter  = /^[\u4e00-\u9fa5]{2,4}$/;   //正则
        self.formEvent(cur,value,filter,"用户名不能为空","用户名错误");
    };
    this.blur_mobile = function(){
        var cur = $(this);
        var value = cur.val();
        var filter  = /^((\+?86)|(\(\+86\)))?(13[012356789][0-9]{8}|15[012356789][0-9]{8}|18[02356789][0-9]{8}|147[0-9]{8}|1349[0-9]{7})$/;
        self.formEvent(cur,value,filter,"手机号不能为空","手机号错误");
    }
    this.blur_email = function(){
        var cur = $(this);
        var value = cur.val();
        var filter  = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;   //正则
        self.formEvent(cur,value,filter,"邮箱不能为空","邮箱错误");
    }
    this.formEvent= function(cur,value,filter,text1,text2){
        if(value==''){
            cur.siblings(".tip-error").show().text(text1)
        }else if(!filter.test(value)){   //正则匹配
            cur.siblings(".tip-error").show().text(text2)
        }else {
            cur.siblings(".tip-error").hide();
        }
    }
    
}

function bind(){
    var self = this;  
    
    this.init = function(){
        //1、成为焦点,错误提示隐藏
        $(".list ul li input").focus(function(){
            $(this).siblings(".tip-error").hide();
        });

        //2、失去焦点,1)是否为空  2)格式校验
        $(".name").blur(this.blur_name);
        $(".mobile").blur(this.blur_mobile);
        $(".email").blur(this.blur_email);
        
        //3)提交   判断
        $(".btn-submit").click(function(){
            var _name=$.trim($(".name").val()),
                _mobile=$.trim($(".mobile").val()),
                _email=$.trim($(".email").val()),
                _age=$.trim($(".age").val()),
                _address=$.trim($(".address").val());
            var data = {
                name:_name,
                mobile:_mobile,
                email:_email,
                age:_age,
                address:_address
            };
            if(_name=="" || _mobile==""||_email=="" || $(".tip-error").is(":visible")){
                alert("请输入正确信息");
            }else {
                $.ajax({
                    type:"post",//请求方式
                    url: "http://localhost:3000/form_info", //请求路径
                    data:data,//传参数
                    dataType:"json",
                    success:function(msg){
                        console.log(msg);
                    },
                    error:function(error){
                        cosnole.log(error);
                    }
                })
            }
                
        })
    }
}


$(function(){
    bind.prototype = new base();
    var valid = new bind();
    valid.init();
})

html

<div class="main">
  <div class="top">
    <div class="">
      <h2>请完善以下信息h2>
    div>
  div>
  <div class="list">
    <ul>
      <li>
        <label>姓名label>
        <input type="text" name="name" class="name" placeholder="输入您的姓名">
        <span class="tip-error">span>
      li>
      <li>
        <label>手机label>
        <input type="text" name="mobile" class="mobile" placeholder="输入您的手机" >
        <span class="tip-error">span>
      li>
      <li>
        <label>电子邮箱label>
        <input type="text" name="email" class="email" placeholder="输入您的电子邮箱">
        <span class="tip-error">span>
      li>
      <li>
        <label>年龄label>
        <input type="text" name="age" class="age" placeholder="输入您的年龄" maxlength="3">
        <span class="tip-error">span>
      li>
      <li>
        <label>通讯地址label>
        <input type="text" name="address" class="address" placeholder="输入您的通讯地址">
        <span class="tip-error">span>
      li>
      <li class="fn-textcenter"><a class="btn-blue btn-submit">提交a>li>
    ul>
  div>
div>

代码中涉及到ajax请求,这个需要启一个node服务,关于ajax和前后台数据交互的分享我会在以后的博文中更新~

效果图如下:
前端学习之JavaScript面向对象(1)——封装_第1张图片

小生乃牛犊一枚,如有不对,欢迎各路大佬下方评论指正

你可能感兴趣的:(前端学习,JavaScript)