JavaScript学习笔记之JS对象(2)


<!DOCTYPE html>
<html>
  <head>
    <title>emailConfirm.html</title>
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="this is my page">
    <meta http-equiv="content-type" content="text/html; charset=UTF-8">
    <!--<link type="text/css" href="https://www.jb51.net/article/styles.css">-->
    <script type="text/javascript">
        function isEmail()
        {
            var emailValue = document.getElementsByName("email")[0].value;
            if(-1 == emailValue.indexOf("@"))
            {
                alert("请填写正确的Email地址");
            }
            else
            {
                alert("Ok");
            }
        }
    </script>
  </head>
  <body>
      <form>
        email: <input type="text"><br/>
        <input type="button" value="check">
    </form>
  </body>
</html>

自定义对象
  前面讲函数的时候讲过一个例子,现在这里再讲一下这个例子:

复制代码 代码如下:


<!DOCTYPE html>
<html>
  <head>
    <title>objectTest.html</title>
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="this is my page">
    <meta http-equiv="content-type" content="text/html; charset=UTF-8">
    <!--<link type="text/css" href="https://www.jb51.net/article/styles.css">-->
  </head>
  <body>
    <script type="text/javascript">
    //定义对象的一种方式:通过构造函数
        function member(name, gender)
        {
            //属性
            this.name = name;
            this.gender = gender;
            //方法
            this.display = display;//指定member对象的display方法
        }
        function display()
        {
            var str = this.name + " : " + this.gender;
            //这个display方法被谁使用了,此处的this就指向那个对象
            document.writeln(str + "<br/>");
        }
        //生成对象
        var m1 = new member("zhangsan", "male");
        var m2 = new member("lisi", "male");
        var m3 = new member("wangwu", "male");
        var m4 = new member("wangfang", "female");
        with(document)
        {
            write("输出属性","<br/>");
            write(m1.name + ":" + m1.gender + "<br/>");
            write(m2.name + ":" + m2.gender + "<br/>");
            write(m3.name + ":" + m3.gender + "<br/>");
            write(m4.name + ":" + m4.gender + "<br/>");
        }
        document.write("调用方法","<br/>");
        m1.display();
        m2.display();
        m3.display();
        m4.display();
    </script>
  </body>
</html>

小伙伴们是否对javascript中对象的概念和用法有了新的认识了呢,希望大家能够喜欢本文及本系列文章。

您可能感兴趣的文章:

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wgxyjf.html