zoukankan      html  css  js  c++  java
  • javascript中的类

    一、在构造函数中定义属性

    二、在原形对象中定义共享方法

    完整实例:

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
    <script language="JavaScript">
        function sc(name,age,score) {
            //定义构造函数
            this.name = name
            this.age = age
            this.score = score
        }
        sc.prototype.display_score = function (){   //定义共享方法
            document.writeln("姓名:",this.name," ")
            document.writeln("年龄:",this.age," ")
            document.writeln("分数:",this.score,"<br>")
        }
        var s = new sc("张三",20,100)    //实例化一个对象,必须用new关键字
        s.display_score()    //调用共享方法
    
    
        function SC(name,age,sex,score) {   //(封装)
            //定义子类构造函数,继承自sc
            sc.call(this,name,age,score);
            this.sex = sex
        }
    
        SC.prototype = new sc()     //(继承)
        var S = new SC("李四",21,"男",100);
        S.display_score()//调用父类的display_score()
    
        //重定义子类自己的display_score()  (多态)
        SC.prototype.display_score = function () {
            document.writeln("姓名:",this.name," ")
            document.writeln("年龄:",this.age," ")
            document.writeln("性别:",this.sex," ")
            document.writeln("分数:",this.score,"<br>")
        }
        S.display_score()   //调用子类的display_socre()
        
    </script>
    </body>
    </html>
    

      输出结果:

    姓名:张三 年龄:20 分数:100
    姓名:李四 年龄:21 分数:100
    姓名:李四 年龄:21 性别:男 分数:100
    

      

  • 相关阅读:
    Neoj4安装使用教程
    毕业设计每日博客——第五周3
    毕业设计每日博客——第五周2
    不知道为什么,我就是被这个冒号迷惑了
    对items函数的理解
    关于运算符+的一点想法
    请使用迭代查找一个list中最小和最大值,并返回一个tuple
    Python中最常见括号()、[]、{}的区别
    ping和telnet的区别
    SQL注入原理
  • 原文地址:https://www.cnblogs.com/ldy-miss/p/8637911.html
Copyright © 2011-2022 走看看