Take a look at GW

【JavaScript】获取未知类的结构

目录结构:

contents structure [+]

为什么需要获取类结构的代码

笔者认为主要是方便,如果一个项目很大或是引用了其它地方的js文件,如果顺着src文件查找会很麻烦。为了对代码理解的更好,还需要对javaScript的类有所了解,更多情况读者可以参考JavaScript定义类的三种方法

关于javascript中对类的简介

其实Javascript中没有类这个定义,但是有类这个概念。很多人都写过这样的代码,就是一个关键字 function,然后定义一个方法名,方法名后紧跟一对括号。

定义类的方法

第一种

function Cat() {
    this.name = "大毛";
}

或是

Cat.prototype.makeSound = function(){
  alert("喵喵喵");
}

然后通过

var cat = new Cat();

创建对象,和

cat.makeSound();

来调用。

第二种

通过Object.create()创建

  var cat={
    name:"guaiguai"
  }
  var q=Object.create(cat);

不过这种方式下,也可以直接用

cat.name

调用。

Demo

HTML页面

<!DOCTYPE html>
<html>
  <head>
    <title>showProperty.html</title>

    <meta name="content-type" content="text/html; charset=UTF-8">

    <script src="date.js"></script>
  </head>
  
  <body>
  <h1>show Object detail</h1>
  <script>

    var num=new date();
    
    var property="<h2>property:</h2>";
    var functions="<h2>function:</h2>";
    var complete="<h2>complete:</h2>"
        
    //get complete information
    complete=complete+date;
    
    //through function and property
   for(prop in num){
     if(typeof(num[prop])=="function"){
       functions=functions+prop+":"+num[prop]+"<br>";
     }else
       property=property+prop+":"+num[prop]+"<br>";
   }
   //print
   document.write(complete+"<br>"+property+"<br>"+functions);
   
  </script>
  </body>
</html>

data文件

function date() {
    var year;
    var month;
    var day;
    this.year=new Date().getFullYear();
    this.month=new Date().getMonth();
    this.day=new Date().getDate();
    var fun;
    
    this.fun=function(){
        alert("I am coming fun1");
        this.year=new Date().getFullYear()-1;
        this.month=new Date().getMonth()-1;
        this.day=new Date().getDay()-1;
    }
}

注意事项

上面这段代码只能测试从外面连接进来的js文件里的类,而js自带的类就不行,比如:将上面的

var num=new date();

换成

var num=new Date();

就不行,这种情况下是不会显示时间类的结构的,除非在覆盖后,才会显示。

参考文章

 http://www.ruanyifeng.com/blog/2012/07/three_ways_to_define_a_javascript_class.html

 http://www.jb51.net/article/20430.htm

 http://www.cnblogs.com/xcj26/archive/2013/04/08/3006023.html

 

本文为博主原创文章,如需转载请注明出处。

posted @ 2016-12-17 17:52  HDWK  阅读(774)  评论(0编辑  收藏  举报