zoukankan      html  css  js  c++  java
  • js类

      1  js类

    js中类的定义有点不一样,不过暂时可以只研究一下: 如何创建 JavaScript 对象的模板 (template),使用js对象模板时候创建的对象类似与类的定义(包含属性和方法).

      

    <html>
    <head>
    
    </head>
    <body>
    
    <script type="text/javascript">
    
    function People(name)//创建对象的模板,相当与类定义
    {
        this.name = name;//为对象属性赋值
        this.SetName = function(newname){ //对象方法(内部直接定义)
        document.writeln("old name:" + name + "<br />");
        this.name = newname;
        document.writeln("new name:" + name + "<br />");
        }
    }
    
    var p = new People("zhangsan");
    document.writeln("name:" + p.name + "<br />");
    p.SetName("lisi");
    
    </script>
    </body>
    </html>

      运行这段代码即可看到显示的姓名。

      2  javascript的方法可以分为三类:类方法,对象方法,原型方法。

    看下面的代码:

    <html>
    <head>
    
    </head>
    <body>
    
    <script type="text/javascript">
    
    function People(name)
    {
    this.name=name;
    //对象方法
    this.Introduce=function(){
    document.write("对象方法说:" + this.name + "<br \>");
    }
    }
    //类方法
    People.Run=function(){
    document.write("类方法说:" + this.name + "<br \>");
    }
    //原型方法
    People.prototype.IntroduceChinese=function(){
    document.write("原型方法说:" + this.name + "<br \>");
    }
    
    //测试
    
    var p1=new People("张三");
    
    p1.Introduce();
    
    People.Run();
    
    p1.IntroduceChinese();
    
    </script>
    
    </body>
    </html>

    输出结果是: 张三    People   张三

    至于类方法为什么会输出People?我也不知道为什么?

      3  prototype含义

    javascript中的每个对象都有prototype属性,Javascript中对象的prototype属性的解释是:返回对象类型原型的引用。

      A.prototype = new B();理解prototype不应把它和继承混淆。A的prototype为B的一个实例,可以理解A将B中的方法和属性全部克隆了一遍。A能使用B的方法和属性。这里强调的是克隆而不是继承。

    <html>
    <head>
    
    </head>
    <body>
    
    <script type="text/javascript">
    function baseClass()  //基类
    {
    this.showMsg = function()
    {
         alert("baseClass::showMsg");   
    }
    }
    
    function extendClass()  
    {
    this.fun = function()
    {
        document.write("extendClass::Method");
    }
    }
    
    extendClass.prototype = new baseClass();  //扩展类克隆基类所有的方法
    
    instance = new extendClass();
    
    instance.showMsg(); // 显示baseClass::showMsg
    instance.fun();  //调用自己的方法
    
    </script>
    
    </body>
    </html>

    我们首先定义了baseClass类,然后我们要定义extentClass,但是我们打算以baseClass的一个实例为原型,来克隆的extendClass也同时包含showMsg这个对象方法。

      文章参考地址:http://www.cnblogs.com/yjf512/archive/2011/06/03/2071914.html

  • 相关阅读:
    集群间如何实现session共享
    详解PHP如何实现单点登录
    jsonp原理详解
    跨站请求CSRF攻击
    防止SQL注入
    在springboot中使用h2数据库
    Datalab实验
    飞步无人驾驶2018届校园招聘在线笔试A轮
    HDU6030 Happy Necklace
    HDU5950 Recursive sequence
  • 原文地址:https://www.cnblogs.com/wang7/p/2616594.html
Copyright © 2011-2022 走看看